<?php namespace {function load_config($file,$parse=CONF_PARSE){ $ext = pathinfo($file,PATHINFO_EXTENSION); switch($ext){ case 'php': return include $file; case 'ini': return parse_ini_file($file); case 'yaml': return yaml_parse_file($file); case 'xml': return (array)simplexml_load_file($file); case 'json': return json_decode(file_get_contents($file), true); default: if(function_exists($parse)){ return $parse($file); }else{ E(L('_NOT_SUPPORT_').':'.$ext); } } } if (!function_exists('yaml_parse_file')) { function yaml_parse_file($file) { vendor('spyc.Spyc'); return Spyc::YAMLLoad($file); } } function E($msg, $code=0) { throw new Think\Exception($msg, $code); } function G($start,$end='',$dec=4) { static $_info = array(); static $_mem = array(); if(is_float($end)) { $_info[$start] = $end; }elseif(!empty($end)){ if(!isset($_info[$end])) $_info[$end] = microtime(TRUE); if(MEMORY_LIMIT_ON && $dec=='m'){ if(!isset($_mem[$end])) $_mem[$end] = memory_get_usage(); return number_format(($_mem[$end]-$_mem[$start])/1024); }else{ return number_format(($_info[$end]-$_info[$start]),$dec); } }else{ $_info[$start] = microtime(TRUE); if(MEMORY_LIMIT_ON) $_mem[$start] = memory_get_usage(); } return null; } function L($name=null, $value=null) { static $_lang = array(); if (empty($name)) return $_lang; if (is_string($name)) { $name = strtoupper($name); if (is_null($value)){ return isset($_lang[$name]) ? $_lang[$name] : $name; }elseif(is_array($value)){ $replace = array_keys($value); foreach($replace as &$v){ $v = '{$'.$v.'}'; } return str_replace($replace,$value,isset($_lang[$name]) ? $_lang[$name] : $name); } $_lang[$name] = $value; return null; } if (is_array($name)) $_lang = array_merge($_lang, array_change_key_case($name, CASE_UPPER)); return null; } function trace($value='[think]',$label='',$level='DEBUG',$record=false) { return Think\Think::trace($value,$label,$level,$record); } function compile($filename) { $content = php_strip_whitespace($filename); $content = trim(substr($content, 5)); $content = preg_replace('/\/\/\[RUNTIME\](.*?)\/\/\[\/RUNTIME\]/s', '', $content); if(0===strpos($content,'namespace')){ $content = preg_replace('/namespace\s(.*?);/','namespace \\1{',$content,1); }else{ $content = 'namespace {'.$content; } if ('?>' == substr($content, -2)) $content = substr($content, 0, -2); return $content.'}'; } function T($template='',$layer=''){ if(false === strpos($template,'://')){ $template = 'http://'.str_replace(':', '/',$template); } $info = parse_url($template); $file = $info['host'].(isset($info['path'])?$info['path']:''); $module = isset($info['user'])?$info['user'].'/':MODULE_NAME.'/'; $extend = $info['scheme']; $layer = $layer?$layer:C('DEFAULT_V_LAYER'); $auto = C('AUTOLOAD_NAMESPACE'); if($auto && isset($auto[$extend])){ $baseUrl = $auto[$extend].$module.$layer.'/'; }elseif(C('VIEW_PATH')){ $baseUrl = C('VIEW_PATH'); }elseif(defined('TMPL_PATH')){ $baseUrl = TMPL_PATH.$module; }else{ $baseUrl = APP_PATH.$module.$layer.'/'; } $theme = substr_count($file,'/')<2 ? C('DEFAULT_THEME') : ''; $depr = C('TMPL_FILE_DEPR'); if('' == $file) { $file = CONTROLLER_NAME . $depr . ACTION_NAME; }elseif(false === strpos($file, '/')){ $file = CONTROLLER_NAME . $depr . $file; }elseif('/' != $depr){ $file = substr_count($file,'/')>1 ? substr_replace($file,$depr,strrpos($file,'/'),1) : str_replace('/', $depr, $file); } return $baseUrl.($theme?$theme.'/':'').$file.C('TMPL_TEMPLATE_SUFFIX'); } function I($name,$default='',$filter=null,$datas=null) { if(strpos($name,'.')) { list($method,$name) = explode('.',$name,2); }else{ $method = 'param'; } switch(strtolower($method)) { case 'get' : $input =& $_GET;break; case 'post' : $input =& $_POST;break; case 'put' : parse_str(file_get_contents('php://input'), $input);break; case 'param' : switch($_SERVER['REQUEST_METHOD']) { case 'POST': $input = $_POST; break; case 'PUT': parse_str(file_get_contents('php://input'), $input); break; default: $input = $_GET; } break; case 'path' : $input = array(); if(!empty($_SERVER['PATH_INFO'])){ $depr = C('URL_PATHINFO_DEPR'); $input = explode($depr,trim($_SERVER['PATH_INFO'],$depr)); } break; case 'request' : $input =& $_REQUEST; break; case 'session' : $input =& $_SESSION; break; case 'cookie' : $input =& $_COOKIE; break; case 'server' : $input =& $_SERVER; break; case 'globals' : $input =& $GLOBALS; break; case 'data' : $input =& $datas; break; default: return NULL; } if(''==$name) { $data = $input; array_walk_recursive($data,'filter_exp'); $filters = isset($filter)?$filter:C('DEFAULT_FILTER'); if($filters) { if(is_string($filters)){ $filters = explode(',',$filters); } foreach($filters as $filter){ $data = array_map_recursive($filter,$data); } } }elseif(isset($input[$name])) { $data = $input[$name]; is_array($data) && array_walk_recursive($data,'filter_exp'); $filters = isset($filter)?$filter:C('DEFAULT_FILTER'); if($filters) { if(is_string($filters)){ $filters = explode(',',$filters); }elseif(is_int($filters)){ $filters = array($filters); } foreach($filters as $filter){ if(function_exists($filter)) { $data = is_array($data)?array_map_recursive($filter,$data):$filter($data); }else{ $data = filter_var($data,is_int($filter)?$filter:filter_id($filter)); if(false === $data) { return isset($default)?$default:NULL; } } } } }else{ $data = isset($default)?$default:NULL; } return $data; } function array_map_recursive($filter, $data) { $result = array(); foreach ($data as $key => $val) { $result[$key] = is_array($val) ? array_map_recursive($filter, $val) : call_user_func($filter, $val); } return $result; } function N($key, $step=0,$save=false) { static $_num = array(); if (!isset($_num[$key])) { $_num[$key] = (false !== $save)? S('N_'.$key) : 0; } if (empty($step)){ return $_num[$key]; }else{ $_num[$key] = $_num[$key] + (int)$step; } if(false !== $save){ S('N_'.$key,$_num[$key],$save); } return null; } function parse_name($name, $type=0) { if ($type) { return ucfirst(preg_replace_callback('/_([a-zA-Z])/', function($match){return strtoupper($match[1]);}, $name)); } else { return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_")); } } function require_cache($filename) { static $_importFiles = array(); if (!isset($_importFiles[$filename])) { if (file_exists_case($filename)) { require $filename; $_importFiles[$filename] = true; } else { $_importFiles[$filename] = false; } } return $_importFiles[$filename]; } function file_exists_case($filename) { if (is_file($filename)) { if (IS_WIN && APP_DEBUG) { if (basename(realpath($filename)) != basename($filename)) return false; } return true; } return false; } function import($class, $baseUrl = '', $ext=EXT) { static $_file = array(); $class = str_replace(array('.', '#'), array('/', '.'), $class); if (isset($_file[$class . $baseUrl])) return true; else $_file[$class . $baseUrl] = true; $class_strut = explode('/', $class); if (empty($baseUrl)) { if ('@' == $class_strut[0] || MODULE_NAME == $class_strut[0]) { $baseUrl = MODULE_PATH; $class = substr_replace($class, '', 0, strlen($class_strut[0]) + 1); }elseif (in_array($class_strut[0],array('Think','Org','Behavior','Com','Vendor')) || is_dir(LIB_PATH.$class_strut[0])) { $baseUrl = LIB_PATH; }else { $baseUrl = APP_PATH; } } if (substr($baseUrl, -1) != '/') $baseUrl .= '/'; $classfile = $baseUrl . $class . $ext; if (!class_exists(basename($class),false)) { return require_cache($classfile); } return null; } function load($name, $baseUrl='', $ext='.php') { $name = str_replace(array('.', '#'), array('/', '.'), $name); if (empty($baseUrl)) { if (0 === strpos($name, '@/')) { $baseUrl = MODULE_PATH.'Common/'; $name = substr($name, 2); } else { $array = explode('/', $name); $baseUrl = APP_PATH . array_shift($array).'/Common/'; $name = implode('/',$array); } } if (substr($baseUrl, -1) != '/') $baseUrl .= '/'; require_cache($baseUrl . $name . $ext); } function vendor($class, $baseUrl = '', $ext='.php') { if (empty($baseUrl)) $baseUrl = VENDOR_PATH; return import($class, $baseUrl, $ext); } function D($name='',$layer='') { if(empty($name)) return new Think\Model; static $_model = array(); $layer = $layer? : C('DEFAULT_M_LAYER'); if(isset($_model[$name.$layer])) return $_model[$name.$layer]; $class = parse_res_name($name,$layer); if(class_exists($class)) { $model = new $class(basename($name)); }elseif(false === strpos($name,'/')){ if(!C('APP_USE_NAMESPACE')){ import('Common/'.$layer.'/'.$class); }else{ $class = '\\Common\\'.$layer.'\\'.$name.$layer; } $model = class_exists($class)? new $class($name) : new Think\Model($name); }else { Think\Log::record('D方法实例化没找到模型类'.$class,Think\Log::NOTICE); $model = new Think\Model(basename($name)); } $_model[$name.$layer] = $model; return $model; } function M($name='', $tablePrefix='',$connection='') { static $_model = array(); if(strpos($name,':')) { list($class,$name) = explode(':',$name); }else{ $class = 'Think\\Model'; } $guid = (is_array($connection)?implode('',$connection):$connection).$tablePrefix . $name . '_' . $class; if (!isset($_model[$guid])) $_model[$guid] = new $class($name,$tablePrefix,$connection); return $_model[$guid]; } function parse_res_name($name,$layer,$level=1){ if(strpos($name,'://')) { list($extend,$name) = explode('://',$name); }else{ $extend = ''; } if(strpos($name,'/') && substr_count($name, '/')>=$level){ list($module,$name) = explode('/',$name,2); }else{ $module = defined('MODULE_NAME') ? MODULE_NAME : '' ; } $array = explode('/',$name); $class = $module.'\\'.$layer; foreach($array as $name){ $class .= '\\'.parse_name($name, 1); } if($extend){ $class = $extend.'\\'.$class; } return $class.$layer; } function controller($name,$path=''){ $layer = C('DEFAULT_C_LAYER'); if(!C('APP_USE_NAMESPACE')){ $class = parse_name($name, 1).$layer; import(MODULE_NAME.'/'.$layer.'/'.$class); }else{ $class = ( $path ? basename(ADDON_PATH).'\\'.$path : MODULE_NAME ).'\\'.$layer; $array = explode('/',$name); foreach($array as $name){ $class .= '\\'.parse_name($name, 1); } $class .= $layer; } if(class_exists($class)) { return new $class(); }else { return false; } } function A($name,$layer='',$level=0) { static $_action = array(); $layer = $layer? : C('DEFAULT_C_LAYER'); $level = $level? : ($layer == C('DEFAULT_C_LAYER')?C('CONTROLLER_LEVEL'):1); if(isset($_action[$name.$layer])) return $_action[$name.$layer]; $class = parse_res_name($name,$layer,$level); if(class_exists($class)) { $action = new $class(); $_action[$name.$layer] = $action; return $action; }else { return false; } } function R($url,$vars=array(),$layer='') { $info = pathinfo($url); $action = $info['basename']; $module = $info['dirname']; $class = A($module,$layer); if($class){ if(is_string($vars)) { parse_str($vars,$vars); } return call_user_func_array(array(&$class,$action.C('ACTION_SUFFIX')),$vars); }else{ return false; } } function tag($tag, &$params=NULL) { return \Think\Hook::listen($tag,$params); } function B($name, &$params=NULL) { if(strpos($name,'/')){ list($name,$tag) = explode('/',$name); }else{ $tag = 'run'; } return \Think\Hook::exec($name,$tag,$params); } function strip_whitespace($content) { $stripStr = ''; $tokens = token_get_all($content); $last_space = false; for ($i = 0, $j = count($tokens); $i < $j; $i++) { if (is_string($tokens[$i])) { $last_space = false; $stripStr .= $tokens[$i]; } else { switch ($tokens[$i][0]) { case T_COMMENT: case T_DOC_COMMENT: break; case T_WHITESPACE: if (!$last_space) { $stripStr .= ' '; $last_space = true; } break; case T_START_HEREDOC: $stripStr .= "<<<THINK\n"; break; case T_END_HEREDOC: $stripStr .= "THINK;\n"; for($k = $i+1; $k < $j; $k++) { if(is_string($tokens[$k]) && $tokens[$k] == ';') { $i = $k; break; } else if($tokens[$k][0] == T_CLOSE_TAG) { break; } } break; default: $last_space = false; $stripStr .= $tokens[$i][1]; } } } return $stripStr; } function throw_exception($msg, $type='Think\\Exception', $code=0) { Think\Log::record('建议使用E方法替代throw_exception',Think\Log::NOTICE); if (class_exists($type, false)) throw new $type($msg, $code); else Think\Think::halt($msg); } function dump($var, $echo=true, $label=null, $strict=true) { $label = ($label === null) ? '' : rtrim($label) . ' '; if (!$strict) { if (ini_get('html_errors')) { $output = print_r($var, true); $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>'; } else { $output = $label . print_r($var, true); } } else { ob_start(); var_dump($var); $output = ob_get_clean(); if (!extension_loaded('xdebug')) { $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output); $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>'; } } if ($echo) { echo($output); return null; }else return $output; } function layout($layout) { if(false !== $layout) { C('LAYOUT_ON',true); if(is_string($layout)) { C('LAYOUT_NAME',$layout); } }else{ C('LAYOUT_ON',false); } } function U($url='',$vars='',$suffix=true,$domain=true) { $info = parse_url($url); if (isset ( $_GET ['_addons'] ) && strpos ( $info ['path'], '/' ) === false) { $info['query'] = '_addons='.$_GET['_addons'].'&_controller='.$_GET['_controller'].'&_action='.$info['path'].'&'.$info['query']; $info['path'] = 'home/addons/execute'; } $url = !empty($info['path'])?$info['path']:ACTION_NAME; if(isset($info['fragment'])) { $anchor = $info['fragment']; if(false !== strpos($anchor,'?')) { list($anchor,$info['query']) = explode('?',$anchor,2); } if(false !== strpos($anchor,'@')) { list($anchor,$host) = explode('@',$anchor, 2); } }elseif(false !== strpos($url,'@')) { list($url,$host) = explode('@',$info['path'], 2); } if(isset($host)) { $domain = $host.(strpos($host,'.')?'':strstr($_SERVER['HTTP_HOST'],'.')); }elseif($domain===true){ $domain = $_SERVER['HTTP_HOST']; if(C('APP_SUB_DOMAIN_DEPLOY') ) { $domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.'); foreach (C('APP_SUB_DOMAIN_RULES') as $key => $rule) { $rule = is_array($rule)?$rule[0]:$rule; if(false === strpos($key,'*') && 0=== strpos($url,$rule)) { $domain = $key.strstr($domain,'.'); $url = substr_replace($url,'',0,strlen($rule)); break; } } } } if(is_string($vars)) { parse_str($vars,$vars); }elseif(!is_array($vars)){ $vars = array(); } if(isset($info['query'])) { parse_str($info['query'],$params); $vars = array_merge($params,$vars); } $depr = C('URL_PATHINFO_DEPR'); if($url) { if(0=== strpos($url,'/')) { $route = true; $url = substr($url,1); if('/' != $depr) { $url = str_replace('/',$depr,$url); } }else{ if('/' != $depr) { $url = str_replace('/',$depr,$url); } $url = trim($url,$depr); $path = explode($depr,$url); $var = array(); $var[C('VAR_ACTION')] = !empty($path)?array_pop($path):ACTION_NAME; $var[C('VAR_CONTROLLER')] = !empty($path)?array_pop($path):CONTROLLER_NAME; if($maps = C('URL_ACTION_MAP')) { if(isset($maps[strtolower($var[C('VAR_CONTROLLER')])])) { $maps = $maps[strtolower($var[C('VAR_CONTROLLER')])]; if($action = array_search(strtolower($var[C('VAR_ACTION')]),$maps)){ $var[C('VAR_ACTION')] = $action; } } } if($maps = C('URL_CONTROLLER_MAP')) { if($controller = array_search(strtolower($var[C('VAR_CONTROLLER')]),$maps)){ $var[C('VAR_CONTROLLER')] = $controller; } } if(C('URL_CASE_INSENSITIVE')) { $var[C('VAR_CONTROLLER')] = parse_name($var[C('VAR_CONTROLLER')]); } $module = ''; if(!empty($path)) { $var[C('VAR_MODULE')] = array_pop($path); }else{ if(C('MULTI_MODULE')) { if(MODULE_NAME != C('DEFAULT_MODULE') || !C('MODULE_ALLOW_LIST')){ $var[C('VAR_MODULE')]= MODULE_NAME; } } } if($maps = C('URL_MODULE_MAP')) { if($_module = array_search(strtolower($var[C('VAR_MODULE')]),$maps)){ $var[C('VAR_MODULE')] = $_module; } } if(isset($var[C('VAR_MODULE')])){ $module = $var[C('VAR_MODULE')]; unset($var[C('VAR_MODULE')]); } } } if(C('URL_MODEL') == 0) { $url = __APP__.'?'.C('VAR_MODULE')."={$module}&".http_build_query(array_reverse($var)); if(C('URL_CASE_INSENSITIVE')){ $url = strtolower($url); } if(!empty($vars)) { $vars = http_build_query($vars); $url .= '&'.$vars; } }else{ $module = defined('BIND_MODULE') ? '' : $module; if(isset($route)) { $url = __APP__.'/'.($module?$module.MODULE_PATHINFO_DEPR:'').rtrim($url,$depr); }else{ $url = __APP__.'/'.($module?$module.MODULE_PATHINFO_DEPR:'').implode($depr,array_reverse($var)); } if(C('URL_CASE_INSENSITIVE')){ $url = strtolower($url); } if(!empty($vars)) { foreach ($vars as $var => $val){ if('' !== trim($val)) $url .= $depr . $var . $depr . urlencode($val); } } if($suffix) { $suffix = $suffix===true?C('URL_HTML_SUFFIX'):$suffix; if($pos = strpos($suffix, '|')){ $suffix = substr($suffix, 0, $pos); } if($suffix && '/' != substr($url,-1)){ $url .= '.'.ltrim($suffix,'.'); } } } if(isset($anchor)){ $url .= '#'.$anchor; } if($domain) { $url = (is_ssl()?'https://':'http://').$domain.$url; } $re = C('URL_ROUTE_RULES'); if ( C('URL_ROUTER_ON') && isset($re['Addons/execute/:_addons/:_controller/:_action'])) { $url = str_ireplace(array('home/addons/execute','_addons/','_controller/','_action/'), array('addon',''), $url); } return $url; } function W($name, $data=array()) { if(isset($data['one_param'])){ $data = array($data); } return R($name,$data,'Widget'); } function is_ssl() { if(isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))){ return true; }elseif(isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'] )) { return true; } return false; } function redirect($url, $time=0, $msg='') { $url = str_replace(array("\n", "\r"), '', $url); if (empty($msg)) $msg = "系统将在{$time}秒之后自动跳转到{$url}！"; if (!headers_sent()) { if (0 === $time) { header('Location: ' . $url); } else { header("refresh:{$time};url={$url}"); echo($msg); } exit(); } else { $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>"; if ($time != 0) $str .= $msg; exit($str); } } function S($name,$value='',$options=null) { static $cache = ''; if(is_array($options) && empty($cache)){ $type = isset($options['type'])?$options['type']:''; $cache = Think\Cache::getInstance($type,$options); }elseif(is_array($name)) { $type = isset($name['type'])?$name['type']:''; $cache = Think\Cache::getInstance($type,$name); return $cache; }elseif(empty($cache)) { $cache = Think\Cache::getInstance(); } if(''=== $value){ return $cache->get($name); }elseif(is_null($value)) { return $cache->rm($name); }else { if(is_array($options)) { $expire = isset($options['expire'])?$options['expire']:NULL; }else{ $expire = is_numeric($options)?$options:NULL; } return $cache->set($name, $value, $expire); } } function F($name, $value='', $path=DATA_PATH) { static $_cache = array(); $filename = $path . $name . '.php'; if ('' !== $value) { if (is_null($value)) { if(false !== strpos($name,'*')){ return false; }else{ unset($_cache[$name]); return Think\Storage::unlink($filename,'F'); } } else { Think\Storage::put($filename,serialize($value),'F'); $_cache[$name] = $value; return null; } } if (isset($_cache[$name])) return $_cache[$name]; if (Think\Storage::has($filename,'F')){ $value = unserialize(Think\Storage::read($filename,'F')); $_cache[$name] = $value; } else { $value = false; } return $value; } function to_guid_string($mix) { if (is_object($mix)) { return spl_object_hash($mix); } elseif (is_resource($mix)) { $mix = get_resource_type($mix) . strval($mix); } else { $mix = serialize($mix); } return md5($mix); } function xml_encode($data, $root='think', $item='item', $attr='', $id='id', $encoding='utf-8') { if(is_array($attr)){ $_attr = array(); foreach ($attr as $key => $value) { $_attr[] = "{$key}=\"{$value}\""; } $attr = implode(' ', $_attr); } $attr = trim($attr); $attr = empty($attr) ? '' : " {$attr}"; $xml = "<?xml version=\"1.0\" encoding=\"{$encoding}\"?>"; $xml .= "<{$root}{$attr}>"; $xml .= data_to_xml($data, $item, $id); $xml .= "</{$root}>"; return $xml; } function data_to_xml($data, $item='item', $id='id') { $xml = $attr = ''; foreach ($data as $key => $val) { if(is_numeric($key)){ $id && $attr = " {$id}=\"{$key}\""; $key = $item; } $xml .= "<{$key}{$attr}>"; $xml .= (is_array($val) || is_object($val)) ? data_to_xml($val, $item, $id) : $val; $xml .= "</{$key}>"; } return $xml; } function session($name='',$value='') { $prefix = C('SESSION_PREFIX'); if(is_array($name)) { if(isset($name['prefix'])) C('SESSION_PREFIX',$name['prefix']); if(C('VAR_SESSION_ID') && isset($_REQUEST[C('VAR_SESSION_ID')])){ session_id($_REQUEST[C('VAR_SESSION_ID')]); }elseif(isset($name['id'])) { session_id($name['id']); } if('common' != APP_MODE){ ini_set('session.auto_start', 0); } if(isset($name['name'])) session_name($name['name']); if(isset($name['path'])) session_save_path($name['path']); if(isset($name['domain'])) ini_set('session.cookie_domain', $name['domain']); if(isset($name['expire'])) ini_set('session.gc_maxlifetime', $name['expire']); if(isset($name['use_trans_sid'])) ini_set('session.use_trans_sid', $name['use_trans_sid']?1:0); if(isset($name['use_cookies'])) ini_set('session.use_cookies', $name['use_cookies']?1:0); if(isset($name['cache_limiter'])) session_cache_limiter($name['cache_limiter']); if(isset($name['cache_expire'])) session_cache_expire($name['cache_expire']); if(isset($name['type'])) C('SESSION_TYPE',$name['type']); if(C('SESSION_TYPE')) { $type = C('SESSION_TYPE'); $class = strpos($type,'\\')? $type : 'Think\\Session\\Driver\\'. ucwords(strtolower($type)); $hander = new $class(); session_set_save_handler( array(&$hander,"open"), array(&$hander,"close"), array(&$hander,"read"), array(&$hander,"write"), array(&$hander,"destroy"), array(&$hander,"gc")); } if(C('SESSION_AUTO_START')) session_start(); }elseif('' === $value){ if(''===$name){ return $prefix ? $_SESSION[$prefix] : $_SESSION; }elseif(0===strpos($name,'[')) { if('[pause]'==$name){ session_write_close(); }elseif('[start]'==$name){ session_start(); }elseif('[destroy]'==$name){ $_SESSION = array(); session_unset(); session_destroy(); }elseif('[regenerate]'==$name){ session_regenerate_id(); } }elseif(0===strpos($name,'?')){ $name = substr($name,1); if(strpos($name,'.')){ list($name1,$name2) = explode('.',$name); return $prefix?isset($_SESSION[$prefix][$name1][$name2]):isset($_SESSION[$name1][$name2]); }else{ return $prefix?isset($_SESSION[$prefix][$name]):isset($_SESSION[$name]); } }elseif(is_null($name)){ if($prefix) { unset($_SESSION[$prefix]); }else{ $_SESSION = array(); } }elseif($prefix){ if(strpos($name,'.')){ list($name1,$name2) = explode('.',$name); return isset($_SESSION[$prefix][$name1][$name2])?$_SESSION[$prefix][$name1][$name2]:null; }else{ return isset($_SESSION[$prefix][$name])?$_SESSION[$prefix][$name]:null; } }else{ if(strpos($name,'.')){ list($name1,$name2) = explode('.',$name); return isset($_SESSION[$name1][$name2])?$_SESSION[$name1][$name2]:null; }else{ return isset($_SESSION[$name])?$_SESSION[$name]:null; } } }elseif(is_null($value)){ if($prefix){ unset($_SESSION[$prefix][$name]); }else{ unset($_SESSION[$name]); } }else{ if($prefix){ if (!isset($_SESSION[$prefix])) { $_SESSION[$prefix] = array(); } $_SESSION[$prefix][$name] = $value; }else{ $_SESSION[$name] = $value; } } return null; } function cookie($name='', $value='', $option=null) { $config = array( 'prefix' => C('COOKIE_PREFIX'), 'expire' => C('COOKIE_EXPIRE'), 'path' => C('COOKIE_PATH'), 'domain' => C('COOKIE_DOMAIN'), 'httponly' => C('COOKIE_HTTPONLY'), ); if (!is_null($option)) { if (is_numeric($option)) $option = array('expire' => $option); elseif (is_string($option)) parse_str($option, $option); $config = array_merge($config, array_change_key_case($option)); } if(!empty($config['httponly'])){ ini_set("session.cookie_httponly", 1); } if (is_null($name)) { if (empty($_COOKIE)) return null; $prefix = empty($value) ? $config['prefix'] : $value; if (!empty($prefix)) { foreach ($_COOKIE as $key => $val) { if (0 === stripos($key, $prefix)) { setcookie($key, '', time() - 3600, $config['path'], $config['domain']); unset($_COOKIE[$key]); } } } return null; }elseif('' === $name){ return $_COOKIE; } $name = $config['prefix'] . str_replace('.', '_', $name); if ('' === $value) { if(isset($_COOKIE[$name])){ $value = $_COOKIE[$name]; if(0===strpos($value,'think:')){ $value = substr($value,6); return array_map('urldecode',json_decode(MAGIC_QUOTES_GPC?stripslashes($value):$value,true)); }else{ return $value; } }else{ return null; } } else { if (is_null($value)) { setcookie($name, '', time() - 3600, $config['path'], $config['domain']); unset($_COOKIE[$name]); } else { if(is_array($value)){ $value = 'think:'.json_encode(array_map('urlencode',$value)); } $expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0; setcookie($name, $value, $expire, $config['path'], $config['domain']); $_COOKIE[$name] = $value; } } return null; } function load_ext_file($path) { if($files = C('LOAD_EXT_FILE')) { $files = explode(',',$files); foreach ($files as $file){ $file = $path.'Common/'.$file.'.php'; if(is_file($file)) include $file; } } if($configs = C('LOAD_EXT_CONFIG')) { if(is_string($configs)) $configs = explode(',',$configs); foreach ($configs as $key=>$config){ $file = $path.'Conf/'.$config.CONF_EXT; if(is_file($file)) { is_numeric($key)?C(load_config($file)):C($key,load_config($file)); } } } } function get_client_ip($type = 0,$adv=false) { $type = $type ? 1 : 0; static $ip = NULL; if ($ip !== NULL) return $ip[$type]; if($adv){ if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $pos = array_search('unknown',$arr); if(false !== $pos) unset($arr[$pos]); $ip = trim($arr[0]); }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; }elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } }elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } $long = sprintf("%u",ip2long($ip)); $ip = $long ? array($ip, $long) : array('0.0.0.0', 0); return $ip[$type]; } function send_http_status($code) { static $_status = array( 100 => 'Continue', 101 => 'Switching Protocols', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Moved Temporarily ', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 509 => 'Bandwidth Limit Exceeded' ); if(isset($_status[$code])) { header('HTTP/1.1 '.$code.' '.$_status[$code]); header('Status:'.$code.' '.$_status[$code]); } } function filter_exp(&$value){ if (in_array(strtolower($value),array('exp','or'))){ $value .= ' '; } } function in_array_case($value,$array){ return in_array(strtolower($value),array_map('strtolower',$array)); } function getAddonConfig($name) { static $_config = array (); if (isset ( $_config [$name] )) { return $_config [$name]; } $config = array (); $token = get_token (); if (! empty ( $token )) { $map ['token'] = $token; $addon_config = M ( 'member_public' )->where ( $map )->getField ( 'addon_config' ); $addon_config = json_decode ( $addon_config, true ); if (isset ( $addon_config [$name] )) $config = $addon_config [$name]; unset ( $map ['token'] ); } if (empty ( $config )) { $map ['name'] = $name; $map ['status'] = 1; $config = M ( 'Addons' )->where ( $map )->getField ( 'config' ); $config = json_decode ( $config, true ); } if (!$config) { $temp_arr = include_once ONETHINK_ADDON_PATH . $name . '/config.php'; foreach ( $temp_arr as $key => $value ) { $config [$key] = $temp_arr [$key] ['value']; } } $_config [$name] = $config; return $config; }}namespace {const ONETHINK_VERSION = '1.0.131218'; const ONETHINK_ADDON_PATH = './Addons/'; function is_login() { $user = session ( 'user_auth' ); if (empty ( $user )) { return 0; } else { return session ( 'user_auth_sign' ) == data_auth_sign ( $user ) ? $user ['uid'] : 0; } } function is_administrator($uid = null) { $uid = is_null ( $uid ) ? is_login () : $uid; return $uid && (intval ( $uid ) === C ( 'USER_ADMINISTRATOR' )); } function str2arr($str, $glue = ',') { return explode ( $glue, $str ); } function arr2str($arr, $glue = ',') { return implode ( $glue, $arr ); } function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) { if (function_exists ( "mb_substr" )) $slice = mb_substr ( $str, $start, $length, $charset ); elseif (function_exists ( 'iconv_substr' )) { $slice = iconv_substr ( $str, $start, $length, $charset ); if (false === $slice) { $slice = ''; } } else { $re ['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/"; $re ['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/"; $re ['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/"; $re ['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/"; preg_match_all ( $re [$charset], $str, $match ); $slice = join ( "", array_slice ( $match [0], $start, $length ) ); } return $suffix ? $slice . '...' : $slice; } function msubstr_local($str, $start = 0, $length, $charset = "utf-8") { if (function_exists ( "mb_substr" )) $slice = mb_substr ( $str, $start, $length, $charset ); elseif (function_exists ( 'iconv_substr' )) { $slice = iconv_substr ( $str, $start, $length, $charset ); if (false === $slice) { $slice = ''; } } else { $re ['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/"; $re ['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/"; $re ['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/"; $re ['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/"; preg_match_all ( $re [$charset], $str, $match ); $slice = join ( "", array_slice ( $match [0], $start, $length ) ); } return (strlen ( $str ) > strlen ( $slice )) ? $slice . '...' : $slice; } function think_encrypt($data, $key = '', $expire = 0) { $key = md5 ( empty ( $key ) ? C ( 'DATA_AUTH_KEY' ) : $key ); $data = base64_encode ( $data ); $x = 0; $len = strlen ( $data ); $l = strlen ( $key ); $char = ''; for($i = 0; $i < $len; $i ++) { if ($x == $l) $x = 0; $char .= substr ( $key, $x, 1 ); $x ++; } $str = sprintf ( '%010d', $expire ? $expire + time () : 0 ); for($i = 0; $i < $len; $i ++) { $str .= chr ( ord ( substr ( $data, $i, 1 ) ) + (ord ( substr ( $char, $i, 1 ) )) % 256 ); } return str_replace ( array ( '+', '/', '=' ), array ( '-', '_', '' ), base64_encode ( $str ) ); } function think_decrypt($data, $key = '') { $key = md5 ( empty ( $key ) ? C ( 'DATA_AUTH_KEY' ) : $key ); $data = str_replace ( array ( '-', '_' ), array ( '+', '/' ), $data ); $mod4 = strlen ( $data ) % 4; if ($mod4) { $data .= substr ( '====', $mod4 ); } $data = base64_decode ( $data ); $expire = substr ( $data, 0, 10 ); $data = substr ( $data, 10 ); if ($expire > 0 && $expire < time ()) { return ''; } $x = 0; $len = strlen ( $data ); $l = strlen ( $key ); $char = $str = ''; for($i = 0; $i < $len; $i ++) { if ($x == $l) $x = 0; $char .= substr ( $key, $x, 1 ); $x ++; } for($i = 0; $i < $len; $i ++) { if (ord ( substr ( $data, $i, 1 ) ) < ord ( substr ( $char, $i, 1 ) )) { $str .= chr ( (ord ( substr ( $data, $i, 1 ) ) + 256) - ord ( substr ( $char, $i, 1 ) ) ); } else { $str .= chr ( ord ( substr ( $data, $i, 1 ) ) - ord ( substr ( $char, $i, 1 ) ) ); } } return base64_decode ( $str ); } function data_auth_sign($data) { if (! is_array ( $data )) { $data = ( array ) $data; } ksort ( $data ); $code = http_build_query ( $data ); $sign = sha1 ( $code ); return $sign; } function list_sort_by($list, $field, $sortby = 'asc') { if (is_array ( $list )) { $refer = $resultSet = array (); foreach ( $list as $i => $data ) $refer [$i] = &$data [$field]; switch ($sortby) { case 'asc' : asort ( $refer ); break; case 'desc' : arsort ( $refer ); break; case 'nat' : natcasesort ( $refer ); break; } foreach ( $refer as $key => $val ) $resultSet [] = &$list [$key]; return $resultSet; } return false; } function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) { $tree = array (); if (is_array ( $list )) { $refer = array (); foreach ( $list as $key => $data ) { $refer [$data [$pk]] = & $list [$key]; } foreach ( $list as $key => $data ) { $parentId = $data [$pid]; if ($root == $parentId) { $tree [] = & $list [$key]; } else { if (isset ( $refer [$parentId] )) { $parent = & $refer [$parentId]; $parent [$child] [] = & $list [$key]; } } } } return $tree; } function tree_to_list($tree, $child = '_child', $order = 'id', &$list = array()) { if (is_array ( $tree )) { $refer = array (); foreach ( $tree as $key => $value ) { $reffer = $value; if (isset ( $reffer [$child] )) { unset ( $reffer [$child] ); tree_to_list ( $value [$child], $child, $order, $list ); } $list [] = $reffer; } $list = list_sort_by ( $list, $order, $sortby = 'asc' ); } return $list; } function format_bytes($size, $delimiter = '') { $units = array ( 'B', 'KB', 'MB', 'GB', 'TB', 'PB' ); for($i = 0; $size >= 1024 && $i < 5; $i ++) $size /= 1024; return round ( $size, 2 ) . $delimiter . $units [$i]; } function set_redirect_url($url) { cookie ( 'redirect_url', $url ); } function get_redirect_url() { $url = cookie ( 'redirect_url' ); return empty ( $url ) ? __APP__ : $url; } function hook($hook, $params = array()) { \Think\Hook::listen ( $hook, $params ); } function get_addon_class($name) { $class = "Addons\\{$name}\\{$name}Addon"; return $class; } function get_addon_config($name) { $class = get_addon_class ( $name ); if (class_exists ( $class )) { $addon = new $class (); return $addon->getConfig (); } else { return array (); } } function addons_url($url, $param = array()) { $urlArr = explode ( '://', $url ); if (stripos ( $urlArr [0], '_' ) !== false) { $addons = $urlArr [0]; $url = 'http://' . $urlArr [1]; } $url = parse_url ( $url ); $case = C ( 'URL_CASE_INSENSITIVE' ); ! $addons || $url ['scheme'] = $addons; $addons = $case ? parse_name ( $url ['scheme'] ) : $url ['scheme']; $controller = $case ? parse_name ( $url ['host'] ) : $url ['host']; $action = trim ( $case ? strtolower ( $url ['path'] ) : $url ['path'], '/' ); if (isset ( $url ['query'] )) { parse_str ( $url ['query'], $query ); $param = array_merge ( $query, $param ); } $params = array ( '_addons' => ucfirst ( $addons ), '_controller' => ucfirst ( $controller ), '_action' => $action ); $params = array_merge ( $params, $param ); return U ( 'Home/Addons/execute', $params ); } function time_format($time = NULL, $format = 'Y-m-d H:i') { if (empty ( $time )) return ''; $time = $time === NULL ? NOW_TIME : intval ( $time ); return date ( $format, $time ); } function day_format($time = NULL) { return time_format ( $time, 'Y-m-d' ); } function hour_format($time = NULL) { return time_format ( $time, 'H:i' ); } function get_username($uid = 0) { static $list; if (! ($uid && is_numeric ( $uid ))) { return session ( 'user_auth.username' ); } if (empty ( $list )) { $list = S ( 'sys_active_user_list' ); } $key = "u{$uid}"; if (isset ( $list [$key] )) { $name = $list [$key]; } else { $User = new User\Api\UserApi (); $info = $User->info ( $uid ); if ($info && isset ( $info [1] )) { $name = $list [$key] = $info [1]; $count = count ( $list ); $max = C ( 'USER_MAX_CACHE' ); while ( $count -- > $max ) { array_shift ( $list ); } S ( 'sys_active_user_list', $list ); } else { $name = ''; } } return $name; } function get_nickname($uid = 0) { $info = get_mult_userinfo ( $uid ); return $info ['nickname']; } function get_truename($uid) { $info = D ( 'Home/Member' )->getMemberInfo ( $uid ); return $info ['truename']; } function get_memberinfo($uid) { return D ( 'Home/Member' )->getMemberInfo ( $uid ); } function get_followinfo($id) { return D ( 'Common/Follow' )->getFollowInfo ( $id ); } function get_mult_userinfo($uid) { $info = get_followinfo ( $uid ); if (! $info) { $info = get_memberinfo ( $uid ); } return $info; } function get_mult_username($uids) { is_array ( $uids ) || $uids = explode ( ',', $uids ); $uids = array_filter ( $uids ); if (empty ( $uids )) { return; } foreach ( $uids as $uid ) { $name = get_truename ( $uid ); if ($name) { $nameArr [] = $name; } } return implode ( ', ', $nameArr ); } function get_category($id, $field = null) { static $list; if (empty ( $id ) || ! is_numeric ( $id )) { return ''; } if (empty ( $list )) { $list = S ( 'sys_category_list' ); } if (! isset ( $list [$id] )) { $cate = M ( 'Category' )->find ( $id ); if (! $cate || 1 != $cate ['status']) { return ''; } $list [$id] = $cate; S ( 'sys_category_list', $list ); } return is_null ( $field ) ? $list [$id] : $list [$id] [$field]; } function get_category_name($id) { return get_category ( $id, 'name' ); } function get_category_title($id) { return get_category ( $id, 'title' ); } function get_top_model($model_id = null) { $map = array ( 'status' => 1, 'extend' => 0 ); if (! is_null ( $model_id )) { $map ['id'] = array ( 'neq', $model_id ); } $model = M ( 'Model' )->where ( $map )->field ( true )->select (); foreach ( $model as $value ) { $list [$value ['id']] = $value; } return $list; } function get_document_model($id = null, $field = null) { static $list; if (! (is_numeric ( $id ) || is_null ( $id ))) { return ''; } if (empty ( $list )) { $list = S ( 'DOCUMENT_MODEL_LIST' ); } if (empty ( $list )) { $map = array ( 'status' => 1, 'extend' => 1 ); $model = M ( 'Model' )->where ( $map )->field ( true )->select (); foreach ( $model as $value ) { $list [$value ['id']] = $value; } S ( 'DOCUMENT_MODEL_LIST', $list ); } if (is_null ( $id )) { return $list; } elseif (is_null ( $field )) { return $list [$id]; } else { return $list [$id] [$field]; } } function ubb($data) { return $data; } function action_log($action = null, $model = null, $record_id = null, $user_id = null) { if (empty ( $action ) || empty ( $model ) || empty ( $record_id )) { return '参数不能为空'; } if (empty ( $user_id )) { $user_id = is_login (); } $action_info = M ( 'Action' )->getByName ( $action ); if ($action_info ['status'] != 1) { return '该行为被禁用或删除'; } $data ['action_id'] = $action_info ['id']; $data ['user_id'] = $user_id; $data ['action_ip'] = ip2long ( get_client_ip () ); $data ['model'] = $model; $data ['record_id'] = $record_id; $data ['create_time'] = NOW_TIME; if (! empty ( $action_info ['log'] )) { if (preg_match_all ( '/\[(\S+?)\]/', $action_info ['log'], $match )) { $log ['user'] = $user_id; $log ['record'] = $record_id; $log ['model'] = $model; $log ['time'] = NOW_TIME; $log ['data'] = array ( 'user' => $user_id, 'model' => $model, 'record' => $record_id, 'time' => NOW_TIME ); foreach ( $match [1] as $value ) { $param = explode ( '|', $value ); if (isset ( $param [1] )) { $replace [] = call_user_func ( $param [1], $log [$param [0]] ); } else { $replace [] = $log [$param [0]]; } } $data ['remark'] = str_replace ( $match [0], $replace, $action_info ['log'] ); } else { $data ['remark'] = $action_info ['log']; } } else { $data ['remark'] = '操作url：' . $_SERVER ['REQUEST_URI']; } M ( 'ActionLog' )->add ( $data ); if (! empty ( $action_info ['rule'] )) { $rules = parse_action ( $action, $user_id ); $res = execute_action ( $rules, $action_info ['id'], $user_id ); } } function parse_action($action = null, $self) { if (empty ( $action )) { return false; } if (is_numeric ( $action )) { $map = array ( 'id' => $action ); } else { $map = array ( 'name' => $action ); } $info = M ( 'Action' )->where ( $map )->find (); if (! $info || $info ['status'] != 1) { return false; } $rules = $info ['rule']; $rules = str_replace ( '{$self}', $self, $rules ); $rules = explode ( ';', $rules ); $return = array (); foreach ( $rules as $key => &$rule ) { $rule = explode ( '|', $rule ); foreach ( $rule as $k => $fields ) { $field = empty ( $fields ) ? array () : explode ( ':', $fields ); if (! empty ( $field )) { $return [$key] [$field [0]] = $field [1]; } } if (! array_key_exists ( 'cycle', $return [$key] ) || ! array_key_exists ( 'max', $return [$key] )) { unset ( $return [$key] ['cycle'], $return [$key] ['max'] ); } } return $return; } function execute_action($rules = false, $action_id = null, $user_id = null) { if (! $rules || empty ( $action_id ) || empty ( $user_id )) { return false; } $return = true; foreach ( $rules as $rule ) { $map = array ( 'action_id' => $action_id, 'user_id' => $user_id ); $map ['create_time'] = array ( 'gt', NOW_TIME - intval ( $rule ['cycle'] ) * 3600 ); $exec_count = M ( 'ActionLog' )->where ( $map )->count (); if ($exec_count > $rule ['max']) { continue; } $Model = M ( ucfirst ( $rule ['table'] ) ); $field = $rule ['field']; $res = $Model->where ( $rule ['condition'] )->setField ( $field, array ( 'exp', $rule ['rule'] ) ); if (! $res) { $return = false; } } return $return; } function create_dir_or_files($files) { foreach ( $files as $key => $value ) { if (substr ( $value, - 1 ) == '/') { mkdir ( $value ); } else { @file_put_contents ( $value, '' ); } } } if (! function_exists ( 'array_column' )) { function array_column(array $input, $columnKey, $indexKey = null) { $result = array (); if (null === $indexKey) { if (null === $columnKey) { $result = array_values ( $input ); } else { foreach ( $input as $row ) { $result [] = $row [$columnKey]; } } } else { if (null === $columnKey) { foreach ( $input as $row ) { $result [$row [$indexKey]] = $row; } } else { foreach ( $input as $row ) { $result [$row [$indexKey]] = $row [$columnKey]; } } } return $result; } } function get_table_name($model_id = null) { if (empty ( $model_id )) { return false; } $Model = M ( 'Model' ); $name = ''; $info = $Model->getById ( $model_id ); if ($info ['extend'] != 0) { $name = $Model->getFieldById ( $info ['extend'], 'name' ) . '_'; } $name .= $info ['name']; return $name; } function get_model_attribute($model_id, $group = true) { static $list; if (empty ( $model_id ) || ! is_numeric ( $model_id )) { return ''; } if (! isset ( $list [$model_id] )) { $map = array ( 'model_id' => $model_id ); $extend = M ( 'Model' )->getFieldById ( $model_id, 'extend' ); if ($extend) { $map = array ( 'model_id' => array ( "in", array ( $model_id, $extend ) ) ); } $info = M ( 'Attribute' )->where ( $map )->select (); $list [$model_id] = $info; } $attr = array (); foreach ( $list [$model_id] as $value ) { $attr [$value ['name']] = $value; } if ($group) { $sort = M ( 'Model' )->getFieldById ( $model_id, 'field_sort' ); if (empty ( $sort )) { $group = array ( 1 => array_merge ( $attr ) ); } else { $group = json_decode ( $sort, true ); $keys = array_keys ( $group ); foreach ( $group as $k => $value ) { foreach ( $value as $key => $val ) { unset ( $value [$key] ); $value [$val] = $attr [$val]; unset ( $attr [$val] ); } $group [$k] = $value; } if (! empty ( $attr )) { $group [$keys [0]] = array_merge ( $group [$keys [0]], $attr ); } } $attr = $group; } return $attr; } function api($name, $vars = array()) { $array = explode ( '/', $name ); $method = array_pop ( $array ); $classname = array_pop ( $array ); $module = $array ? array_pop ( $array ) : 'Common'; $callback = $module . '\\Api\\' . $classname . 'Api::' . $method; if (is_string ( $vars )) { parse_str ( $vars, $vars ); } return call_user_func_array ( $callback, $vars ); } function get_table_field($value = null, $condition = 'id', $field = null, $table = null) { if (empty ( $value ) || empty ( $table )) { return false; } $map [$condition] = $value; $info = M ( ucfirst ( $table ) )->where ( $map ); if (empty ( $field )) { $info = $info->field ( true )->find (); } else { $info = $info->getField ( $field ); } return $info; } function get_link($link_id = null, $field = 'url') { $link = ''; if (empty ( $link_id )) { return $link; } $link = M ( 'Url' )->getById ( $link_id ); if (empty ( $field )) { return $link; } else { return $link [$field]; } } function get_cover($cover_id, $field = null) { if (empty ( $cover_id )) return false; $map ['status'] = 1; $picture = M ( 'Picture' )->where ( $map )->getById ( $cover_id ); if (empty ( $picture )) return ''; return empty ( $field ) ? $picture : $picture [$field]; } function get_cover_url($cover_id) { $url = get_cover ( $cover_id, 'path' ); if (empty ( $url )) return ''; return SITE_URL . $url; } function get_picture_url($cover_id) { return get_cover_url ( $cover_id ); } function get_img_html($cover_id) { $url = get_cover_url ( $cover_id ); if (empty ( $url )) return ''; return '<img class="list_img" src="' . $url . '" >'; } function check_document_position($pos = 0, $contain = 0) { if (empty ( $pos ) || empty ( $contain )) { return false; } $res = $pos & $contain; if ($res !== 0) { return true; } else { return false; } } function get_stemma($pids, Model &$model, $field = 'id') { $collection = array (); if (empty ( $pids )) { return $collection; } if (is_array ( $pids )) { $pids = trim ( implode ( ',', $pids ), ',' ); } $result = $model->field ( $field )->where ( array ( 'pid' => array ( 'IN', ( string ) $pids ) ) )->select (); $child_ids = array_column ( ( array ) $result, 'id' ); while ( ! empty ( $child_ids ) ) { $collection = array_merge ( $collection, $result ); $result = $model->field ( $field )->where ( array ( 'pid' => array ( 'IN', $child_ids ) ) )->select (); $child_ids = array_column ( ( array ) $result, 'id' ); } return $collection; } function keyword_unique($keyword) { if (empty ( $keyword )) return false; $map ['keyword'] = $keyword; $info = M ( 'keyword' )->where ( $map )->find (); return empty ( $info ); } function parse_config_attr($string) { $array = preg_split ( '/[;\r\n]+/', trim ( $string, ",;\r\n" ) ); if (strpos ( $string, ':' )) { $value = array (); foreach ( $array as $val ) { list ( $k, $v ) = explode ( ':', $val ); $value [$k] = $v; } } else { $value = $array; } foreach ( $value as &$vo ) { $vo = clean_hide_attr ( $vo ); } return $value; } function clean_hide_attr($str) { $arr = explode ( '|', $str ); return $arr [0]; } function get_hide_attr($str) { $arr = explode ( '|', $str ); return $arr [1]; } function parse_field_attr($string) { if (0 === strpos ( $string, ':' )) { return eval ( substr ( $string, 1 ) . ';' ); } $array = preg_split ( '/[;\r\n]+/', trim ( $string, ",;\r\n" ) ); if (strpos ( $string, ':' )) { $value = array (); foreach ( $array as $val ) { list ( $k, $v ) = explode ( ':', $val ); empty ( $v ) && $v = $k; $k = clean_hide_attr ( $k ); $value [$k] = $v; } } else { $value = $array; } return $value; } function get_list_field($data, $grid, $model) { foreach ( $grid ['field'] as $field ) { $array = explode ( '|', $field ); $array [0] = trim ( $array [0] ); $temp = $data [$array [0]]; if (isset ( $array [1] )) { if ($array [1] == 'get_name_by_status') { $temp = get_name_by_status ( $temp, $array [0], $model ['id'] ); } else { $temp = call_user_func ( $array [1], $temp ); } } $data2 [$array [0]] = $temp; } if (! empty ( $grid ['format'] )) { $value = preg_replace_callback ( '/\[([a-z_]+)\]/', function ($match) use($data2) { return $data2 [$match [1]]; }, $grid ['format'] ); } else { $value = implode ( ' ', $data2 ); } if (! empty ( $grid ['href'] )) { $links = explode ( ',', $grid ['href'] ); foreach ( $links as $link ) { $array = explode ( '|', $link ); $href = $array [0]; if (preg_match ( '/^\[([a-z_]+)\]$/', $href, $matches )) { $val [] = $data2 [$matches [1]]; } else { $show = isset ( $array [1] ) ? $array [1] : $value; $target = '_self'; if (preg_match ( '/target=(\w+)/', $href, $matches )) { $target = $matches [1]; $href = str_replace ( '&' . $matches [0], '', $href ); } $href = str_replace ( array ( '[DELETE]', '[EDIT]', '[MODEL]' ), array ( 'del?id=[id]&model=[MODEL]', 'edit?id=[id]&model=[MODEL]', $model ['id'] ), $href ); $href = preg_replace_callback ( '/\[([a-z_]+)\]/', function ($match) use($data) { return $data [$match [1]]; }, $href ); if (strpos ( $href, '?' ) === false && strpos ( $href, '&' ) !== false) { $href = preg_replace ( "/&/i", "?", $href, 1 ); } if ($show == '删除') { $val [] = '<a class="confirm"   href="' . urldecode ( U ( $href, $GLOBALS ['get_param'] ) ) . '">' . $show . '</a>'; } else { $val [] = '<a  target="' . $target . '" href="' . urldecode ( U ( $href, $GLOBALS ['get_param'] ) ) . '">' . $show . '</a>'; } } } $value = implode ( ' ', $val ); } return $value; } function get_name_by_status($val, $name, $model_id) { static $_name = array (); if (! isset ( $_name [$model_id] )) { $_name [$model_id] = array (); $map ['extra'] = array ( 'EXP', '!=""' ); $map ['model_id'] = $model_id; $list = M ( 'attribute' )->where ( $map )->select (); foreach ( $list as $attr ) { if (empty ( $attr ['extra'] )) continue; $extra = parse_config_attr ( $attr ['extra'] ); if (is_array ( $extra ) && ! empty ( $extra )) { $_name [$model_id] [$attr ['name']] ['value'] = $extra; $_name [$model_id] [$attr ['name']] ['type'] = $attr ['type']; } } } if ($_name [$model_id] [$name] ['type'] == 'checkbox') { $valArr = explode ( ',', $val ); foreach ( $valArr as $v ) { $res [] = empty ( $_name [$model_id] [$name] ['value'] [$v] ) ? $v : $_name [$model_id] [$name] ['value'] [$v]; } return implode ( ', ', $res ); } else { return empty ( $_name [$model_id] [$name] ['value'] [$val] ) ? $val : $_name [$model_id] [$name] ['value'] [$val]; } } function addWeixinLog($data_post = '',$data_type) { $config = getAddonConfig ( 'Journal' ); if(!empty($config['openlog'])){ $log ['cTime'] = time (); $log ['type'] = $data_type; $log ['cData'] = $data_post; $log ['token'] = get_token(); M ( 'weixin_log' )->add ( $log ); } } function getSubByKey($pArray, $pKey = "", $pCondition = "") { $result = array (); if (is_array ( $pArray )) { foreach ( $pArray as $temp_array ) { if (is_object ( $temp_array )) { $temp_array = ( array ) $temp_array; } if (("" != $pCondition && $temp_array [$pCondition [0]] == $pCondition [1]) || "" == $pCondition) { $result [] = ("" == $pKey) ? $temp_array : isset ( $temp_array [$pKey] ) ? $temp_array [$pKey] : ""; } } return $result; } else { return false; } } function isWeixinBrowser() { $agent = $_SERVER ['HTTP_USER_AGENT']; if (! strpos ( $agent, "icroMessenger" )) { return false; } return true; } function GetCurUrl() { $url = 'http://'; if (isset ( $_SERVER ['HTTPS'] ) && $_SERVER ['HTTPS'] == 'on') { $url = 'https://'; } if ($_SERVER ['SERVER_PORT'] != '80') { $url .= $_SERVER ['HTTP_HOST'] . ':' . $_SERVER ['SERVER_PORT'] . $_SERVER ['REQUEST_URI']; } else { $url .= $_SERVER ['HTTP_HOST'] . $_SERVER ['REQUEST_URI']; } if (stripos ( $url, '?' ) === false) { $url .= '?t=' . time (); } return $url; } function get_openid($openid = NULL) { $token = get_token (); if ($openid !== NULL) { session ( 'openid_' . $token, $openid ); } elseif (! empty ( $_REQUEST ['openid'] )) { session ( 'openid_' . $token, $_REQUEST ['openid'] ); } $openid = session ( 'openid_' . $token ); $isWeixinBrowser = isWeixinBrowser (); if (empty ( $openid ) && $isWeixinBrowser) { $callback = GetCurUrl (); OAuthWeixin ( $callback ); } if (empty ( $openid )) { return - 1; } return $openid; } function get_token($token = NULL) { if ($token !== NULL) { session ( 'token', $token ); } elseif (! empty ( $_REQUEST ['token'] )) { session ( 'token', $_REQUEST ['token'] ); } $token = session ( 'token' ); if (empty ( $token )) { return - 1; } return $token; } function get_mid() { return session ( 'mid' ); } function getWeixinUserInfo($openid, $token) { $access_token = get_access_token ( $token ); if (empty ( $access_token )) { return false; } $param2 ['access_token'] = $access_token; $param2 ['openid'] = $openid; $param2 ['lang'] = 'zh_CN'; $url = 'https://api.weixin.qq.com/cgi-bin/user/info?' . http_build_query ( $param2 ); $content = file_get_contents ( $url ); $content = json_decode ( $content, true ); return $content; } function get_token_appinfo($token = '') { empty ( $token ) && $token = get_token (); $map ['token'] = $token; $info = M ( 'member_public' )->where ( $map )->find (); return $info; } function get_token_type($token = '') { $info = get_token_appinfo ( $token ); return intval ( $info ['type'] ); } function get_access_token($token = '') { empty ( $token ) && $token = get_token (); $key = 'access_token_' . $token; $res = S ( $key ); addWeixinLog($key.'access_token:'.$res ,"缓存access_token"); if ($res !== false) return $res; $info = get_token_appinfo ( $token ); if (empty ( $info ['appid'] ) || empty ( $info ['secret'] )) { S ( $key, 0, 7000 ); return 0; } addWeixinLog( $info ['appid']."|".$info ['secret'] ,"进入重新获取access_token"); $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $info ['appid'] . '&secret=' . $info ['secret']; $tempArr = json_decode ( file_get_contents ( $url ), true ); if (@array_key_exists ( 'access_token', $tempArr )) { S ( $key, $tempArr ['access_token'], 7000 ); addWeixinLog('access_token:'.$tempArr ['access_token'] ,"重新获取access_token"); return $tempArr ['access_token']; } else { addWeixinLog(json_encode($tempArr) ,"重新获取access_token失败"); return 0; } } function OAuthWeixin($callback) { $isWeixinBrowser = isWeixinBrowser (); $info = get_token_appinfo (); if (! $isWeixinBrowser || $info ['type'] != 2 || empty ( $info ['appid'] )) { redirect ( $callback . '&openid=-1' ); } $param ['appid'] = $info ['appid']; if (! isset ( $_GET ['getOpenId'] )) { $param ['redirect_uri'] = $callback . '&getOpenId=1'; $param ['response_type'] = 'code'; $param ['scope'] = 'snsapi_base'; $param ['state'] = 123; $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' . http_build_query ( $param ) . '#wechat_redirect'; redirect ( $url ); } elseif ($_GET ['state']) { $param ['secret'] = $info ['secret']; $param ['code'] = I ( 'code' ); $param ['grant_type'] = 'authorization_code'; $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' . http_build_query ( $param ); $content = file_get_contents ( $url ); $content = json_decode ( $content, true ); redirect ( $callback . '&openid=' . $content ['openid'] ); } } function execute_sql_file($sql_path) { $sql = wp_file_get_contents ( $sql_path ); $sql = str_replace ( "\r", "\n", $sql ); $sql = explode ( ";\n", $sql ); $orginal = 'wp_'; $prefix = C ( 'DB_PREFIX' ); $sql = str_replace ( "{$orginal}", "{$prefix}", $sql ); foreach ( $sql as $value ) { $value = trim ( $value ); if (empty ( $value )) continue; $res = M ()->execute ( $value ); } } function set_user_status($addon, $keywordArr = array()) { $user_status ['addon'] = $addon; $user_status ['keywordArr'] = $keywordArr; $openid = get_openid (); return S ( 'user_status_' . $openid, $user_status ); } function get_public_group_name($group_id) { static $_public_group_name; $group_id = intval ( $group_id ); if (! isset ( $_public_group_name [$group_id] )) { $group_list = M ( 'member_public_group' )->field ( 'id, title' )->select (); foreach ( $group_list as $g ) { $_public_group_name [$g ['id']] = $g ['title']; } $_public_group_name [0] = '无'; } return $_public_group_name [$group_id]; } function getShort($str, $length = 40, $ext = '') { $str = htmlspecialchars ( $str ); $str = strip_tags ( $str ); $str = htmlspecialchars_decode ( $str ); $strlenth = 0; $out = ''; preg_match_all ( "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/", $str, $match ); foreach ( $match [0] as $v ) { preg_match ( "/[\xe0-\xef][\x80-\xbf]{2}/", $v, $matchs ); if (! empty ( $matchs [0] )) { $strlenth += 1; } elseif (is_numeric ( $v )) { $strlenth += 0.5; } else { $strlenth += 0.5; } if ($strlenth > $length) { $output .= $ext; break; } $output .= $v; } return $output; } function wp_file_get_contents($url) { $context = stream_context_create ( array ( 'http' => array ( 'timeout' => 30 ) ) ) ; return file_get_contents ( $url, 0, $context ); } function safe($text, $type = 'html') { $text_tags = ''; $link_tags = '<a>'; $image_tags = '<img>'; $font_tags = '<i><b><u><s><em><strong><font><big><small><sup><sub><bdo><h1><h2><h3><h4><h5><h6>'; $base_tags = $font_tags . '<p><br><hr><a><img><map><area><pre><code><q><blockquote><acronym><cite><ins><del><center><strike>'; $form_tags = $base_tags . '<form><input><textarea><button><select><optgroup><option><label><fieldset><legend>'; $html_tags = $base_tags . '<meta><ul><ol><li><dl><dd><dt><table><caption><td><th><tr><thead><tbody><tfoot><col><colgroup><div><span><object><embed><param>'; $all_tags = $form_tags . $html_tags . '<!DOCTYPE><html><head><title><body><base><basefont><script><noscript><applet><object><param><style><frame><frameset><noframes><iframe>'; $text = html_entity_decode ( $text, ENT_QUOTES, 'UTF-8' ); $text = strip_tags ( $text, ${$type . '_tags'} ); if ($type != 'all') { while ( preg_match ( '/(<[^><]+)(ondblclick|onclick|onload|onerror|unload|onmouseover|onmouseup|onmouseout|onmousedown|onkeydown|onkeypress|onkeyup|onblur|onchange|onfocus|background|codebase|dynsrc|lowsrc)([^><]*)/i', $text, $mat ) ) { $text = str_ireplace ( $mat [0], $mat [1] . $mat [3], $text ); } while ( preg_match ( '/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i', $text, $mat ) ) { $text = str_ireplace ( $mat [0], $mat [1] . $mat [3], $text ); } } return $text; } function mkdirs($dir) { if (! is_dir ( $dir )) { if (! mkdirs ( dirname ( $dir ) )) { return false; } if (! mkdir ( $dir, 0777 )) { return false; } } return true; } function getIdsForMap($ids, $map = array(), $field = 'id') { $ids = safe ( $ids ); $ids = preg_split ( '/[\s,;]+/', $ids ); $ids = array_filter ( $ids ); if (empty ( $ids )) return $map; $map [$field] = array ( 'in', $ids ); return $map; } function getCommonCategoryTitle($ids) { $extra = 'type=db&table=common_category'; return getCascadeTitle ( $ids, $extra ); } function getCascadeTitle($ids, $extra) { $idArr = explode ( ',', $ids ); $idArr = array_filter ( $idArr ); if (empty ( $idArr )) return ''; parse_str ( $extra, $arr ); if ($arr ['type'] == 'db') { $table = $arr ['table']; unset ( $arr ['type'], $arr ['table'] ); $arr ['token'] = get_token (); $arr ['id'] = array ( 'in', $idArr ); $list = M ( $table )->where ( $arr )->field ( 'title' )->select (); $titleArr = getSubByKey ( $list, 'title' ); } else { $str = str_replace ( '，', ',', $extra ); $str = str_replace ( '【', '[', $str ); $str = str_replace ( '】', ']', $str ); $str = str_replace ( '：', ':', $str ); $arr = StringToArray ( $str ); $str = ''; foreach ( $arr as $v ) { if ($v == '[' || $v == ']' || $v == ',') { if ($str) { $block = explode ( ':', trim ( $str ) ); if (in_array ( $block [0], $idArr )) { $titleArr [] = isset ( $block [1] ) ? $block [1] : $block [0]; } } $str = ''; } else { $str .= $v; } } } return implode ( ' > ', $titleArr ); } function StringToArray($str) { $result = array (); $len = strlen ( $str ); $i = 0; while ( $i < $len ) { $chr = ord ( $str [$i] ); if ($chr == 9 || $chr == 10 || (32 <= $chr && $chr <= 126)) { $result [] = substr ( $str, $i, 1 ); $i += 1; } elseif (192 <= $chr && $chr <= 223) { $result [] = substr ( $str, $i, 2 ); $i += 2; } elseif (224 <= $chr && $chr <= 239) { $result [] = substr ( $str, $i, 3 ); $i += 3; } elseif (240 <= $chr && $chr <= 247) { $result [] = substr ( $str, $i, 4 ); $i += 4; } elseif (248 <= $chr && $chr <= 251) { $result [] = substr ( $str, $i, 5 ); $i += 5; } elseif (252 <= $chr && $chr <= 253) { $result [] = substr ( $str, $i, 6 ); $i += 6; } } return $result; } function add_credit($name, $lock_time = 5, $credit = array(), $admin_uid = 0) { if (empty ( $name )) return false; if ($lock_time > 0) { $key = 'credit_lock_' . get_token () . '_' . get_openid () . '_' . $name; if (S ( $key )) return false; S ( $key, 1, $lock_time ); } $data ['credit_name'] = $name; $data ['admin_uid'] = $admin_uid; $data = array_merge ( $data, $credit ); $credit = D ( 'Common/Credit' )->addCredit ( $data ); } function getPublicMax($uid) { $map ['uid'] = $uid; $public_count = M ( 'member' )->where ( $map )->getField ( 'public_count' ); if ($public_count === NULL) { $public_count = C ( 'DEFAULT_PUBLIC_CREATE_MAX_NUMB' ); } return intval ( $public_count ); } function diyPage($keyword) { $map ['keyword'] = $keyword; $map ['token'] = get_token (); $page = M ( 'diy' )->where ( $map )->find (); if (! $page) { $map ['token'] = '0'; $page = M ( 'diy' )->where ( $map )->find (); } if (! $page) { return false; } $model = A ( 'Addons://Diy/Diy' ); $model->show ( $page ['id'] ); } function event_url($addon_title, $id = '0') { $map ['token'] = get_token (); $map ['addon_condition'] = array ( 'exp', "='[{$addon_title}:*]' or addon_condition='[{$addon_title}:{$id}]'" ); $event = M ( 'Scratch' )->where ( $map )->order ( 'id desc' )->find (); $event_url = ''; if ($event) { $param ['token'] = get_token (); $param ['openid'] = get_openid (); $param ['id'] = $event ['id']; $event_url = addons_url ( 'Scratch://Scratch/show', $param ); } return $event_url; } function addon_condition_check($addon_condition) { preg_match_all ( "/\[([\s\S]*):([\*,\d]*)\]/i", $addon_condition, $match ); if (empty ( $match [1] [0] ) || empty ( $match [2] [0] )) { return true; } $conditon ['token'] = get_token (); $conditon ['uid'] = get_mid (); switch ($match [1] [0]) { case '投票' : $match [2] [0] != '*' && $match [2] [0] > 0 && $conditon ['vote_id'] = $match [2] [0]; $conditon ['user_id'] = get_mid (); unset ( $conditon ['uid'] ); $res = M ( 'vote_log' )->where ( $conditon )->find (); break; case '通用表单' : $match [2] [0] != '*' && $match [2] [0] > 0 && $conditon ['forms_id'] = $match [2] [0]; $res = M ( 'forms_value' )->where ( $conditon )->find (); break; case '微考试' : $match [2] [0] != '*' && $match [2] [0] > 0 && $conditon ['exam_id'] = $match [2] [0]; $res = M ( 'exam_answer' )->where ( $conditon )->find (); break; case '微测试' : $match [2] [0] != '*' && $match [2] [0] > 0 && $conditon ['test_id'] = $match [2] [0]; $res = M ( 'test_answer' )->where ( $conditon )->find (); break; case '微调研' : $match [2] [0] != '*' && $match [2] [0] > 0 && $conditon ['survey_id'] = $match [2] [0]; $res = M ( 'survey_answer' )->where ( $conditon )->find (); break; default : $match [2] [0] != '*' && $match [2] [0] > 0 && $conditon ['id'] = $match [2] [0]; $res = M ( $match [1] [0] )->where ( $conditon )->find (); } return ! empty ( $res ); } function condition_tips($addon_condition) { if (empty ( $addon_condition )) return ''; preg_match_all ( "/\[([\s\S]*):([\*,\d]*)\]/i", $addon_condition, $match ); if (empty ( $match [1] [0] ) || empty ( $match [2] [0] )) { return ''; } $conditon ['token'] = get_token (); $conditon ['id'] = $match [2] [0]; $title = ''; $has_title = $conditon ['id'] != '*' && $conditon ['id'] > 0; switch ($match [1] [0]) { case '投票' : $has_title && $title = M ( 'vote' )->where ( $conditon )->getField ( 'title' ); break; case '通用表单' : $has_title && $title = M ( 'forms' )->where ( $conditon )->getField ( 'title' ); break; case '微考试' : $has_title && $title = M ( 'exam' )->where ( $conditon )->getField ( 'title' ); break; case '微测试' : $has_title && $title = M ( 'test' )->where ( $conditon )->getField ( 'title' ); break; case '微调研' : $has_title && $title = M ( 'survey' )->where ( $conditon )->getField ( 'title' ); break; default : $has_title && $title = M ( $match [1] [0] )->where ( $conditon )->getField ( 'title' ); } $result = '需要参与' . $title . $match [1] [0] . '后才能领取'; return $result; } function lastsql() { dump ( M ()->getLastSql () ); } function code_decode($text) { $key = substr ( C ( 'WEIPHP_STORE_LICENSE' ), 0, 5 ); return think_decrypt ( $text, $key ); } function outExcel($dataArr, $fileName = '', $sheet = false) { require_once VENDOR_PATH . 'download-xlsx.php'; export_csv ( $dataArr, $fileName, $sheet ); unset ( $sheet ); unset ( $dataArr ); } function category_title($cate_id) { static $_category_title = array (); if (isset ( $_category_title [$cate_id] )) { return $_category_title [$cate_id]; } $map ['token'] = get_token (); $list = M ( 'common_category' )->where ( $map )->field ( 'id,title' )->select (); foreach ( $list as $v ) { $_category_title [$v ['id']] = $v ['title']; } if (! isset ( $_category_title [$cate_id] )) { $_category_title [$cate_id] = ''; } return $_category_title [$cate_id]; } function get_lecturer_name($lecturer_id) { static $_lecturer_name = array (); if (isset ( $_lecturer_name [$lecturer_id] )) { return $_lecturer_name [$lecturer_id]; } $map ['token'] = get_token (); $list = M ( 'classes_lecturer' )->where ( $map )->field ( 'id,name' )->select (); foreach ( $list as $v ) { $_lecturer_name [$v ['id']] = $v ['name']; } if (! isset ( $_lecturer_name [$lecturer_id] )) { $_lecturer_name [$lecturer_id] = ''; } return $_lecturer_name [$lecturer_id]; } function check_token_purview($table, $id, $field = 'token') { $token = get_token (); $map ['id'] = $id; $info = M ( $table )->where ( $map )->field ( $field )->find (); if ($info === false || $info [$field] == $token) return true; exit ( '非法访问' ); } function wp_explode($string, $delimiter = "\s,;\r\n") { if (empty ( $string )) return array (); $string = iconv ( 'utf-8', 'gbk', $string ); $string = preg_replace ( '/\xa3([\xa1-\xfe])/e', 'chr(ord(\1)-0x80)', $string ); $string = iconv ( 'gbk', 'utf-8', $string ); $arr = preg_split ( '/[' . $delimiter . ']+/', $string ); return array_unique ( array_filter ( $arr ) ); } function get_code_img($qr_code) { if (! $qr_code) return ''; $html = '<img src="' . $qr_code . '" width="50" height="50" />'; return $html; } function get_file_title($attach_ids) { $ids = wp_explode ( $attach_ids ); if (empty ( $ids )) return ''; $map ['id'] = array ( 'in', $ids ); $names = M ( 'file' )->where ( $map )->getFields ( 'name' ); return implode ( ', ', $names ); } function num2cn($number) { $number = intval ( $number ); $capnum = array ( "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" ); $capdigit = array ( "", "十", "百", "千", "万" ); $data_arr = str_split ( $number ); $count = count ( $data_arr ); for($i = 0; $i < $count; $i ++) { $d = $capnum [$data_arr [$i]]; $arr [] = $d != '零' ? $d . $capdigit [$count - $i - 1] : $d; } $cncap = implode ( "", $arr ); $cncap = preg_replace ( "/(零)+/", "0", $cncap ); $cncap = trim ( $cncap, '0' ); $cncap = str_replace ( "0", "零", $cncap ); $cncap == '一十' && $cncap = '十'; $cncap == '' && $cncap = '零'; return $cncap; } function week_name($number = null) { if ($number === null) $number = date ( 'w' ); $arr = array ( "日", "一", "二", "三", "四", "五", "六" ); return '星期' . $arr [$number]; } function daytoweek($day = null) { $day === null && $day = date ( 'Y-m-d' ); if (empty ( $day )) return ''; $number = date ( 'w', strtotime ( $day ) ); return week_name ( $number ); } function int_to_string(&$data, $map = array('status'=>array(1=>'正常',-1=>'删除',0=>'禁用',2=>'未审核',3=>'草稿'))) { if ($data === false || $data === null) { return $data; } $data = ( array ) $data; foreach ( $data as $key => $row ) { foreach ( $map as $col => $pair ) { if (isset ( $row [$col] ) && isset ( $pair [$row [$col]] )) { $data [$key] [$col . '_text'] = $pair [$row [$col]]; } } } return $data; } function importFormExcel($attach_id, $column) { $res = array ( 'status' => 0, 'data' => '' ); if (empty ( $attach_id ) || ! is_numeric ( $attach_id )) { $res ['data'] = '上传文件ID无效！'; return $res; } $file = M ( 'file' )->where ( 'id=' . $attach_id )->find (); $root = C ( 'DOWNLOAD_UPLOAD.rootPath' ); $filename = SITE_PATH . '/Uploads/Download/' . $file ['savepath'] . $file ['savename']; if (! file_exists ( $filename )) { $res ['data'] = '上传的文件失败'; return $res; } $extend = $file ['ext']; if (! ($extend == 'xls' || $extend == 'xlsx')) { $res ['data'] = '文件格式不对，请上传xls,xlsx格式的文件'; return $res; } vendor ( 'PHPExcel' ); vendor ( 'PHPExcel.PHPExcel_IOFactory' ); vendor ( 'PHPExcel.Reader.Excel5' ); $format = strtolower ( $extend ) == 'xls' ? 'Excel5' : 'excel2007'; $objReader = \PHPExcel_IOFactory::createReader ( $format ); $objPHPExcel = $objReader->load ( $filename ); $objPHPExcel->setActiveSheetIndex ( 0 ); $sheet = $objPHPExcel->getSheet ( 0 ); $highestRow = $sheet->getHighestRow (); for($j = 2; $j <= $highestRow; $j ++) { $addData = array (); foreach ( $column as $k => $v ) { $addData [$v] = trim ( ( string ) $objPHPExcel->getActiveSheet ()->getCell ( $k . $j )->getValue () ); } $isempty = true; foreach ( $column as $v ) { $isempty && $isempty = empty ( $addData [$v] ); } if (! $isempty) $result [$j] = $addData; } $res ['status'] = 1; $res ['data'] = $result; return $res; } function showNewIcon($time, $day = 3) { $img = ''; if (NOW_TIME < ($time + 86400 * $day)) { $img = '<img src="' . C ( 'TMPL_PARSE_STRING.__IMG__' ) . '/new.png"/>'; } return $img; } function replace_url($content) { $param ['token'] = get_token (); $param ['openid'] = get_openid (); $sreach = array ( '[follow]', '[website]', '[token]', '[openid]' ); $replace = array ( addons_url ( 'UserCenter://UserCenter/bind', $param ), addons_url ( 'WeiSite://WeiSite/index', $param ), $param ['token'], $param ['openid'] ); $content = str_replace ( $sreach, $replace, $content ); return $content; } function check_category($id) { if (is_array ( $id )) { $type = get_category ( $id ['category_id'], 'type' ); $type = explode ( ",", $type ); return in_array ( $id ['type'], $type ); } else { $publish = get_category ( $id, 'allow_publish' ); return $publish ? true : false; } } function check_category_model($info) { $cate = get_category ( $info ['category_id'] ); $array = explode ( ',', $info ['pid'] ? $cate ['model_sub'] : $cate ['model'] ); return in_array ( $info ['model_id'], $array ); } function get_rand_char($length = 6) { $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; $strLength = 61; for($i = 0; $i < $length; $i ++) { $res .= $str [rand ( 0, $strLength )]; } return $res; } function getDistance($lat1, $lng1, $lat2, $lng2) { $earthRadius = 6367000; $lat1 = ($lat1 * pi ()) / 180; $lng1 = ($lng1 * pi ()) / 180; $lat2 = ($lat2 * pi ()) / 180; $lng2 = ($lng2 * pi ()) / 180; $calcLongitude = $lng2 - $lng1; $calcLatitude = $lat2 - $lat1; $stepOne = pow ( sin ( $calcLatitude / 2 ), 2 ) + cos ( $lat1 ) * cos ( $lat2 ) * pow ( sin ( $calcLongitude / 2 ), 2 ); $stepTwo = 2 * asin ( min ( 1, sqrt ( $stepOne ) ) ); $calculatedDistance = $earthRadius * $stepTwo; return round ( $calculatedDistance ); } function short_url($long_url) { $access_token = get_access_token ( $token ); if (empty ( $access_token )) { return $long_url; } $url = 'https://api.weixin.qq.com/cgi-bin/shorturl?access_token=' . $access_token; $data ['action'] = 'long2short'; $data ['long_url'] = $long_url; $ch = curl_init (); curl_setopt ( $ch, CURLOPT_URL, $url ); curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" ); curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE ); curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE ); curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 ); curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 ); curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data ); curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true ); $res = curl_exec ( $ch ); curl_close ( $ch ); $res = json_decode ( $res, true ); if ($res ['errcode'] == 0) { return $res ['short_url']; } else { return $long_url; } } function get_name_by_touxiang($val) { if (!empty($val)) { return ('<img height="48px" src="' . $val . '" />'); } else { return ('<img height="48px" src="' . ADDON_PUBLIC_PATH . '/face.png" />'); } } function exportExcel($expTitle,$expCellName,$expTableData){ $xlsTitle = iconv('utf-8', 'gb2312', $expTitle); $fileName = $_SESSION['account'].date('_YmdHis'); $cellNum = count($expCellName); $dataNum = count($expTableData); vendor("PHPExcel"); $objPHPExcel = new PHPExcel(); $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ'); $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1'); for($i=0;$i<$cellNum;$i++){ $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]); } for($i=0;$i<$dataNum;$i++){ for($j=0;$j<$cellNum;$j++){ $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]); } } header('pragma:public'); header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"'); header("Content-Disposition:attachment;filename=$fileName.xls"); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); return $objWriter; } function getSignPackage($token = '') { empty ( $token ) && $token = get_token (); $info = get_token_appinfo ( $token ); $access_token=get_access_token(); $jsapiTicket =getJsApiTicket($info ['appid'],$access_token); $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $timestamp = time(); $nonceStr =createNonceStr(); $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url"; $signature = sha1($string); $signPackage = array( "appId" => $info ['appid'], "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature, "rawString" => $string ); return $signPackage; } function createNonceStr($length = 16) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $str = ""; for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } return $str; } function getJsApiTicket($appId,$access_token) { $key = 'jsapi_ticket_' . $appId; $res = S ( $key ); addWeixinLog($key.'jsapi_ticket:'.$res ,"缓存取jsapi_ticket"); if ($res !== false){ return $res; } $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$access_token"; $res = json_decode(httpGet($url),true); addWeixinLog(json_encode($res) ,"重新获取jsapi签名原始数据"); if ($res['ticket']) { S ( $key, $res['ticket'], 7000 ); addWeixinLog('ticket:'.$res['ticket'] ,"重新获取jsapi_ticket"); return $res['ticket']; } else { return 0; } } function httpGet($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 500); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_URL, $url); $res = curl_exec($curl); curl_close($curl); return $res; } function curlPost($url, $data){ $ch = curl_init(); $header = "Accept-Charset: utf-8"; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_AUTOREFERER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $tmpInfo = curl_exec($ch); return $tmpInfo; }}namespace Think{ class Hook { static private $tags = array(); static public function add($tag,$name) { if(!isset(self::$tags[$tag])){ self::$tags[$tag] = array(); } if(is_array($name)){ self::$tags[$tag] = array_merge(self::$tags[$tag],$name); }else{ self::$tags[$tag][] = $name; } } static public function import($data,$recursive=true) { if(!$recursive){ self::$tags = array_merge(self::$tags,$data); }else{ foreach ($data as $tag=>$val){ if(!isset(self::$tags[$tag])) self::$tags[$tag] = array(); if(!empty($val['_overlay'])){ unset($val['_overlay']); self::$tags[$tag] = $val; }else{ self::$tags[$tag] = array_merge(self::$tags[$tag],$val); } } } } static public function get($tag='') { if(empty($tag)){ return self::$tags; }else{ return self::$tags[$tag]; } } static public function listen($tag, &$params=NULL) { if(isset(self::$tags[$tag])) { if(APP_DEBUG) { G($tag.'Start'); trace('[ '.$tag.' ] --START--','','INFO'); } foreach (self::$tags[$tag] as $name) { APP_DEBUG && G($name.'_start'); $result = self::exec($name, $tag,$params); if(APP_DEBUG){ G($name.'_end'); trace('Run '.$name.' [ RunTime:'.G($name.'_start',$name.'_end',6).'s ]','','INFO'); } if(false === $result) { return ; } } if(APP_DEBUG) { trace('[ '.$tag.' ] --END-- [ RunTime:'.G($tag.'Start',$tag.'End',6).'s ]','','INFO'); } } return; } static public function exec($name, $tag,&$params=NULL) { if(false === strpos($name,'\\')) { $class = "Addons\\{$name}\\{$name}Addon"; }else{ $class = $name.'Behavior'; $tag = 'run'; } $addon = new $class(); return $addon->$tag($params); } }}namespace Think{ class App { static public function init() { load_ext_file(COMMON_PATH); define('NOW_TIME', $_SERVER['REQUEST_TIME']); define('REQUEST_METHOD',$_SERVER['REQUEST_METHOD']); define('IS_GET', REQUEST_METHOD =='GET' ? true : false); define('IS_POST', REQUEST_METHOD =='POST' ? true : false); define('IS_PUT', REQUEST_METHOD =='PUT' ? true : false); define('IS_DELETE', REQUEST_METHOD =='DELETE' ? true : false); Dispatcher::dispatch(); Hook::listen('url_dispatch'); define('IS_AJAX', ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') || !empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')])) ? true : false); C('LOG_PATH',realpath(LOG_PATH).'/'); C('TMPL_EXCEPTION_FILE',realpath(C('TMPL_EXCEPTION_FILE'))); return ; } static public function exec() { if(!preg_match('/^[A-Za-z](\/|\w)*$/',CONTROLLER_NAME)){ $module = false; }else{ $module = A(CONTROLLER_NAME); } if(!$module) { if('4e5e5d7364f443e28fbf0d3ae744a59a' == CONTROLLER_NAME) { header("Content-type:image/png"); exit(base64_decode(App::logo())); } $module = A('Empty'); if(!$module){ E(L('_CONTROLLER_NOT_EXIST_').':'.CONTROLLER_NAME); } } $action = C('ACTION_NAME')?C('ACTION_NAME'):ACTION_NAME; $action .= C('ACTION_SUFFIX'); try{ if(!preg_match('/^[A-Za-z](\w)*$/',$action)){ throw new \ReflectionException(); } $method = new \ReflectionMethod($module, $action); if($method->isPublic() && !$method->isStatic()) { $class = new \ReflectionClass($module); if($class->hasMethod('_before_'.$action)) { $before = $class->getMethod('_before_'.$action); if($before->isPublic()) { $before->invoke($module); } } if(C('URL_PARAMS_BIND') && $method->getNumberOfParameters()>0){ switch($_SERVER['REQUEST_METHOD']) { case 'POST': $vars = array_merge($_GET,$_POST); break; case 'PUT': parse_str(file_get_contents('php://input'), $vars); break; default: $vars = $_GET; } $params = $method->getParameters(); $paramsBindType = C('URL_PARAMS_BIND_TYPE'); foreach ($params as $param){ $name = $param->getName(); if( 1 == $paramsBindType && !empty($vars) ){ $args[] = array_shift($vars); }elseif( 0 == $paramsBindType && isset($vars[$name])){ $args[] = $vars[$name]; }elseif($param->isDefaultValueAvailable()){ $args[] = $param->getDefaultValue(); }else{ E(L('_PARAM_ERROR_').':'.$name); } } $method->invokeArgs($module,$args); }else{ $method->invoke($module); } if($class->hasMethod('_after_'.$action)) { $after = $class->getMethod('_after_'.$action); if($after->isPublic()) { $after->invoke($module); } } }else{ throw new \ReflectionException(); } } catch (\ReflectionException $e) { $method = new \ReflectionMethod($module,'__call'); $method->invokeArgs($module,array($action,'')); } return ; } static public function run() { Hook::listen('app_init'); App::init(); Hook::listen('app_begin'); if(!IS_CLI){ session(C('SESSION_OPTIONS')); } G('initTime'); App::exec(); Hook::listen('app_end'); return ; } static public function logo(){ return 'iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyBpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBXaW5kb3dzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjVERDVENkZGQjkyNDExRTE5REY3RDQ5RTQ2RTRDQUJCIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjVERDVENzAwQjkyNDExRTE5REY3RDQ5RTQ2RTRDQUJCIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6NURENUQ2RkRCOTI0MTFFMTlERjdENDlFNDZFNENBQkIiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6NURENUQ2RkVCOTI0MTFFMTlERjdENDlFNDZFNENBQkIiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz5fx6IRAAAMCElEQVR42sxae3BU1Rk/9+69+8xuNtkHJAFCSIAkhMgjCCJQUi0GtEIVbP8Qq9LH2No6TmfaztjO2OnUdvqHFMfOVFTqIK0vUEEeqUBARCsEeYQkEPJoEvIiELLvvc9z+p27u2F3s5tsBB1OZiebu5dzf7/v/L7f952zMM8cWIwY+Mk2ulCp92Fnq3XvnzArr2NZnYNldDp0Gw+/OEQ4+obQn5D+4Ubb22+YOGsWi/Todh8AHglKEGkEsnHBQ162511GZFgW6ZCBM9/W4H3iNSQqIe09O196dLKX7d1O39OViP/wthtkND62if/wj/DbMpph8BY/m9xy8BoBmQk+mHqZQGNy4JYRwCoRbwa8l4JXw6M+orJxpU0U6ToKy/5bQsAiTeokGKkTx46RRxxEUgrwGgF4MWNNEJCGgYTvpgnY1IJWg5RzfqLgvcIgktX0i8dmMlFA8qCQ5L0Z/WObPLUxT1i4lWSYDISoEfBYGvM+LlMQQdkLHoWRRZ8zYQI62Thswe5WTORGwNXDcGjqeOA9AF7B8rhzsxMBEoJ8oJKaqPu4hblHMCMPwl9XeNWyb8xkB/DDGYKfMAE6aFL7xesZ389JlgG3XHEMI6UPDOP6JHHu67T2pwNPI69mCP4rEaBDUAJaKc/AOuXiwH07VCS3w5+UQMAuF/WqGI+yFIwVNBwemBD4r0wgQiKoFZa00sEYTwss32lA1tPwVxtc8jQ5/gWCwmGCyUD8vRT0sHBFW4GJDvZmrJFWRY1EkrGA6ZB8/10fOZSSj0E6F+BSP7xidiIzhBmKB09lEwHPkG+UQIyEN44EBiT5vrv2uJXyPQqSqO930fxvcvwbR/+JAkD9EfASgI9EHlp6YiHO4W+cAB20SnrFqxBbNljiXf1Pl1K2S0HCWfiog3YlAD5RGwwxK6oUjTweuVigLjyB0mX410mAFnMoVK1lvvUvgt8fUJH0JVyjuvcmg4dE5mUiFtD24AZ4qBVELxXKS+pMxN43kSdzNwudJ+bQbLlmnxvPOQoCugSap1GnSRoG8KOiKbH+rIA0lEeSAg3y6eeQ6XI2nrYnrPM89bUTgI0Pdqvl50vlNbtZxDUBcLBK0kPd5jPziyLdojJIN0pq5/mdzwL4UVvVInV5ncQEPNOUxa9d0TU+CW5l+FoI0GSDKHVVSOs+0KOsZoxwOzSZNFGv0mQ9avyLCh2Hpm+70Y0YJoJVgmQv822wnDC8Miq6VjJ5IFed0QD1YiAbT+nQE8v/RMZfmgmcCRHIIu7Bmcp39oM9fqEychcA747KxQ/AEyqQonl7hATtJmnhO2XYtgcia01aSbVMenAXrIomPcLgEBA4liGBzFZAT8zBYqW6brI67wg8sFVhxBhwLwBP2+tqBQqqK7VJKGh/BRrfTr6nWL7nYBaZdBJHqrX3kPEPap56xwE/GvjJTRMADeMCdcGpGXL1Xh4ZL8BDOlWkUpegfi0CeDzeA5YITzEnddv+IXL+UYCmqIvqC9UlUC/ki9FipwVjunL3yX7dOTLeXmVMAhbsGporPfyOBTm/BJ23gTVehsvXRnSewagUfpBXF3p5pygKS7OceqTjb7h2vjr/XKm0ZofKSI2Q/J102wHzatZkJPYQ5JoKsuK+EoHJakVzubzuLQDepCKllTZi9AG0DYg9ZLxhFaZsOu7bvlmVI5oPXJMQJcHxHClSln1apFTvAimeg48u0RWFeZW4lVcjbQWZuIQK1KozZfIDO6CSQmQQXdpBaiKZyEWThVK1uEc6v7V7uK0ysduExPZx4vysDR+4SelhBYm0R6LBuR4PXts8MYMcJPsINo4YZCDLj0sgB0/vLpPXvA2Tn42Cv5rsLulGubzW0sEd3d4W/mJt2Kck+DzDMijfPLOjyrDhXSh852B+OvflqAkoyXO1cYfujtc/i3jJSAwhgfFlp20laMLOku/bC7prgqW7lCn4auE5NhcXPd3M7x70+IceSgZvNljCd9k3fLjYsPElqLR14PXQZqD2ZNkkrAB79UeJUebFQmXpf8ZcAQt2XrMQdyNUVBqZoUzAFyp3V3xi/MubUA/mCT4Fhf038PC8XplhWnCmnK/ZzyC2BSTRSqKVOuY2kB8Jia0lvvRIVoP+vVWJbYarf6p655E2/nANBMCWkgD49DA0VAMyI1OLFMYCXiU9bmzi9/y5i/vsaTpHPHidTofzLbM65vMPva9HlovgXp0AvjtaqYMfDD0/4mAsYE92pxa+9k1QgCnRVObCpojpzsKTPvayPetTEgBdwnssjuc0kOBFX+q3HwRQxdrOLAqeYRjkMk/trTSu2Z9Lik7CfF0AvjtqAhS4NHobGXUnB5DQs8hG8p/wMX1r4+8xkmyvQ50JVq72TVeXbz3HvpWaQJi57hJYTw4kGbtS+C2TigQUtZUX+X27QQq2ePBZBru/0lxTm8fOOQ5yaZOZMAV+he4FqIMB+LQB0UgMSajANX29j+vbmly8ipRvHeSQoQOkM5iFXcPQCVwDMs5RBCQmaPOyvbNd6uwvQJ183BZQG3Zc+Eiv7vQOKu8YeDmMcJlt2ckyftVeMIGLBCmdMHl/tFILYwGPjXWO3zOfSq/+om+oa7Mlh2fpSsRGLp7RAW3FUVjNHgiMhyE6zBFjM2BdkdJGO7nP1kJXWAtBuBpPIAu7f+hhu7bFXIuC5xWrf0X2xreykOsUyKkF2gwadbrXDcXrfKxR43zGcSj4t/cCgr+a1iy6EjE5GYktUCl9fwfMeylyooGF48bN2IGLTw8x7StS7sj8TF9FmPGWQhm3rRR+o9lhvjJvSYAdfDUevI1M6bnX/OwWaDMOQ8RPgKRo0eulBTdT8AW2kl8e9L7UHghHwMfLiZPNoSpx0yugpQZaFqKWqxVSM3a2pN1SAhC2jf94I7ybBI7EL5A2Wvu5ht3xsoEt4+Ay/abXgCQAxyOeDsDlTCQzy75ohcGgv9Tra9uiymRUYTLrswOLlCdfAQf7HPDQQ4ErAH5EDXB9cMxWYpjtXApRncojS0sbV/cCgHTHwGNBJy+1PQE2x56FpaVR7wfQGZ37V+V+19EiHNvR6q1fRUjqvbjbMq1/qfHxbTrE10ePY2gPFk48D2CVMTf1AF4PXvyYR9dV6Wf7H413m3xTWQvYGhQ7mfYwA5mAX+18Vue05v/8jG/fZX/IW5MKPKtjSYlt0ellxh+/BOCPAwYaeVr0QofZFxJWVWC8znG70au6llVmktsF0bfHF6k8fvZ5esZJbwHwwnjg59tXz6sL/P0NUZDuSNu1mnJ8Vab17+cy005A9wtOpp3i0bZdpJLUil00semAwN45LgEViZYe3amNye0B6A9chviSlzXVsFtyN5/1H3gaNmMpn8Fz0GpYFp6Zw615H/LpUuRQQDMCL82n5DpBSawkvzIdN2ypiT8nSLth8Pk9jnjwdFzH3W4XW6KMBfwB569NdcGX93mC16tTflcArcYUc/mFuYbV+8zY0SAjAVoNErNgWjtwumJ3wbn/HlBFYdxHvSkJJEc+Ngal9opSwyo9YlITX2C/P/+gf8sxURSLR+mcZUmeqaS9wrh6vxW5zxFCOqFi90RbDWq/YwZmnu1+a6OvdpvRqkNxxe44lyl4OobEnpKA6Uox5EfH9xzPs/HRKrTPWdIQrK1VZDU7ETiD3Obpl+8wPPCRBbkbwNtpW9AbBe5L1SMlj3tdTxk/9W47JUmqS5HU+JzYymUKXjtWVmT9RenIhgXc+nroWLyxXJhmL112OdB8GCsk4f8oZJucnvmmtR85mBn10GZ0EKSCMUSAR3ukcXd5s7LvLD3me61WkuTCpJzYAyRurMB44EdEJzTfU271lUJC03YjXJXzYOGZwN4D8eB5jlfLrdWfzGRW7icMPfiSO6Oe7s20bmhdgLX4Z23B+s3JgQESzUDiMboSzDMHFpNMwccGePauhfwjzwnI2wu9zKGgEFg80jcZ7MHllk07s1H+5yojtUQTlH4nFdLKTGwDmPbIklOb1L1zO4T6N8NCuDLFLS/C63c0eNRimZ++s5BMBHxU11jHchI9oFVUxRh/eMDzHEzGYu0Lg8gJ7oS/tFCwoic44fyUtix0n/46vP4bf+//BRgAYwDDar4ncHIAAAAASUVORK5CYII='; } }}namespace Think{ class Dispatcher { static public function dispatch() { $varPath = C ( 'VAR_PATHINFO' ); $varModule = C ( 'VAR_MODULE' ); $varController = C ( 'VAR_CONTROLLER' ); $varAction = C ( 'VAR_ACTION' ); if (isset ( $_GET [$varPath] )) { $_SERVER ['PATH_INFO'] = $_GET [$varPath]; unset ( $_GET [$varPath] ); } elseif (IS_CLI) { $_SERVER ['PATH_INFO'] = isset ( $_SERVER ['argv'] [1] ) ? $_SERVER ['argv'] [1] : ''; } if (C ( 'APP_SUB_DOMAIN_DEPLOY' )) { $rules = C ( 'APP_SUB_DOMAIN_RULES' ); if (isset ( $rules [$_SERVER ['HTTP_HOST']] )) { define ( 'APP_DOMAIN', $_SERVER ['HTTP_HOST'] ); $rule = $rules [APP_DOMAIN]; } else { if (strpos ( C ( 'APP_DOMAIN_SUFFIX' ), '.' )) { $domain = array_slice ( explode ( '.', $_SERVER ['HTTP_HOST'] ), 0, - 3 ); } else { $domain = array_slice ( explode ( '.', $_SERVER ['HTTP_HOST'] ), 0, - 2 ); } if (! empty ( $domain )) { $subDomain = implode ( '.', $domain ); define ( 'SUB_DOMAIN', $subDomain ); $domain2 = array_pop ( $domain ); if ($domain) { $domain3 = array_pop ( $domain ); } if (isset ( $rules [$subDomain] )) { $rule = $rules [$subDomain]; } elseif (isset ( $rules ['*.' . $domain2] ) && ! empty ( $domain3 )) { $rule = $rules ['*.' . $domain2]; $panDomain = $domain3; } elseif (isset ( $rules ['*'] ) && ! empty ( $domain2 ) && 'www' != $domain2) { $rule = $rules ['*']; $panDomain = $domain2; } } } if (! empty ( $rule )) { if (is_array ( $rule )) { list ( $rule, $vars ) = $rule; } $array = explode ( '/', $rule ); $_GET [$varModule] = array_shift ( $array ); define ( 'BIND_MODULE', $_GET [$varModule] ); $domainModule = true; if (! empty ( $array )) { $controller = array_shift ( $array ); if ($controller) { $_GET [$varController] = $controller; $domainController = true; } } if (isset ( $vars )) { parse_str ( $vars, $parms ); if (isset ( $panDomain )) { $pos = array_search ( '*', $parms ); if (false !== $pos) { $parms [$pos] = $panDomain; } } $_GET = array_merge ( $_GET, $parms ); } } } elseif (isset ( $_GET [$varModule] )) { define ( 'BIND_MODULE', $_GET [$varModule] ); } if (! isset ( $_SERVER ['PATH_INFO'] )) { $types = explode ( ',', C ( 'URL_PATHINFO_FETCH' ) ); foreach ( $types as $type ) { if (0 === strpos ( $type, ':' )) { $_SERVER ['PATH_INFO'] = call_user_func ( substr ( $type, 1 ) ); break; } elseif (! empty ( $_SERVER [$type] )) { $_SERVER ['PATH_INFO'] = (0 === strpos ( $_SERVER [$type], $_SERVER ['SCRIPT_NAME'] )) ? substr ( $_SERVER [$type], strlen ( $_SERVER ['SCRIPT_NAME'] ) ) : $_SERVER [$type]; break; } } } if (empty ( $_SERVER ['PATH_INFO'] )) { $_SERVER ['PATH_INFO'] = ''; } $depr = C ( 'URL_PATHINFO_DEPR' ); define ( 'MODULE_PATHINFO_DEPR', $depr ); $info = trim ( $_SERVER ['PATH_INFO'], '/' ); $re = C('URL_ROUTE_RULES'); if (substr ( $info, 0, 6 ) == 'addon/' && C('URL_ROUTER_ON') && isset($re['Addons/execute/:_addons/:_controller/:_action'])) { $info = str_replace ( 'addon/', 'Home/Addons/execute/', $info ); } define ( '__INFO__', $info ); define ( '__EXT__', strtolower ( pathinfo ( $_SERVER ['PATH_INFO'], PATHINFO_EXTENSION ) ) ); if (__INFO__ && C ( 'MULTI_MODULE' ) && ! isset ( $_GET [$varModule] )) { $paths = explode ( $depr, __INFO__, 2 ); $allowList = C ( 'MODULE_ALLOW_LIST' ); $module = preg_replace ( '/\.' . __EXT__ . '$/i', '', $paths [0] ); if (empty ( $allowList ) || (is_array ( $allowList ) && in_array_case ( $module, $allowList ))) { $_GET [$varModule] = $module; $_SERVER ['PATH_INFO'] = isset ( $paths [1] ) ? $paths [1] : ''; } else { $_SERVER ['PATH_INFO'] = __INFO__; } } else { $_SERVER ['PATH_INFO'] = __INFO__; } define ( '__SELF__', strip_tags ( $_SERVER [C ( 'URL_REQUEST_URI' )] ) ); define ( 'MODULE_NAME', self::getModule ( $varModule ) ); if (MODULE_NAME && (! in_array_case ( MODULE_NAME, C ( 'MODULE_DENY_LIST' ) ) || $domainModule) && is_dir ( APP_PATH . MODULE_NAME )) { define ( 'MODULE_PATH', APP_PATH . MODULE_NAME . '/' ); C ( 'CACHE_PATH', CACHE_PATH . MODULE_NAME . '/' ); if (is_file ( MODULE_PATH . 'Conf/config.php' )) C ( include MODULE_PATH . 'Conf/config.php' ); if ('common' != APP_MODE && is_file ( MODULE_PATH . 'Conf/config_' . APP_MODE . '.php' )) C ( include MODULE_PATH . 'Conf/config_' . APP_MODE . '.php' ); if (is_file ( MODULE_PATH . 'Conf/alias.php' )) Think::addMap ( include MODULE_PATH . 'Conf/alias.php' ); if (is_file ( MODULE_PATH . 'Conf/tags.php' )) Hook::import ( include MODULE_PATH . 'Conf/tags.php' ); if (is_file ( MODULE_PATH . 'Common/function.php' )) include MODULE_PATH . 'Common/function.php'; load_ext_file ( MODULE_PATH ); } else { E ( L ( '_MODULE_NOT_EXIST_' ) . ':' . MODULE_NAME ); } if (! IS_CLI) { $urlMode = C ( 'URL_MODEL' ); if ($urlMode == URL_COMPAT) { define ( 'PHP_FILE', _PHP_FILE_ . '?' . $varPath . '=' ); } elseif ($urlMode == URL_REWRITE) { $url = dirname ( _PHP_FILE_ ); if ($url == '/' || $url == '\\') $url = ''; define ( 'PHP_FILE', $url ); } else { define ( 'PHP_FILE', _PHP_FILE_ ); } define ( '__APP__', strip_tags ( PHP_FILE ) ); $moduleName = defined ( 'MODULE_ALIAS' ) ? MODULE_ALIAS : MODULE_NAME; define ( '__MODULE__', (! empty ( $domainModule ) || ! C ( 'MULTI_MODULE' )) ? __APP__ : __APP__ . '/' . (C ( 'URL_CASE_INSENSITIVE' ) ? strtolower ( $moduleName ) : $moduleName) ); } if ('' != $_SERVER ['PATH_INFO'] && (! C ( 'URL_ROUTER_ON' ) || ! Route::check ())) { Hook::listen ( 'path_info' ); if (C ( 'URL_DENY_SUFFIX' ) && preg_match ( '/\.(' . trim ( C ( 'URL_DENY_SUFFIX' ), '.' ) . ')$/i', $_SERVER ['PATH_INFO'] )) { send_http_status ( 404 ); exit (); } if (C ( 'URL_HTML_SUFFIX' )) { $_SERVER ['PATH_INFO'] = preg_replace ( '/\.(' . trim ( C ( 'URL_HTML_SUFFIX' ), '.' ) . ')$/i', '', $_SERVER ['PATH_INFO'] ); } else { $_SERVER ['PATH_INFO'] = preg_replace ( '/\.' . __EXT__ . '$/i', '', $_SERVER ['PATH_INFO'] ); } $depr = C ( 'URL_PATHINFO_DEPR' ); $paths = explode ( $depr, trim ( $_SERVER ['PATH_INFO'], $depr ) ); if (! isset ( $_GET [$varController] )) { if (C ( 'CONTROLLER_LEVEL' ) > 1) { $_GET [$varController] = implode ( '/', array_slice ( $paths, 0, C ( 'CONTROLLER_LEVEL' ) ) ); $paths = array_slice ( $paths, C ( 'CONTROLLER_LEVEL' ) ); } else { $_GET [$varController] = array_shift ( $paths ); } } $_GET [$varAction] = array_shift ( $paths ); $var = array (); if (C ( 'URL_PARAMS_BIND' ) && 1 == C ( 'URL_PARAMS_BIND_TYPE' )) { $var = $paths; } else { preg_replace_callback ( '/(\w+)\/([^\/]+)/', function ($match) use(&$var) { $var [$match [1]] = strip_tags ( $match [2] ); }, implode ( '/', $paths ) ); } $_GET = array_merge ( $var, $_GET ); } define ( 'CONTROLLER_NAME', self::getController ( $varController ) ); define ( 'ACTION_NAME', self::getAction ( $varAction ) ); if (! IS_CLI) { $controllerName = defined ( 'CONTROLLER_ALIAS' ) ? CONTROLLER_ALIAS : CONTROLLER_NAME; define ( '__CONTROLLER__', ! empty ( $domainController ) ? __MODULE__ . $depr : __MODULE__ . $depr . (C ( 'URL_CASE_INSENSITIVE' ) ? strtolower ( $controllerName ) : $controllerName) ); define ( '__ACTION__', __CONTROLLER__ . $depr . (defined ( 'ACTION_ALIAS' ) ? ACTION_ALIAS : ACTION_NAME) ); } $_REQUEST = array_merge ( $_POST, $_GET ); } static private function getController($var) { $controller = (! empty ( $_GET [$var] ) ? $_GET [$var] : C ( 'DEFAULT_CONTROLLER' )); unset ( $_GET [$var] ); if ($maps = C ( 'URL_CONTROLLER_MAP' )) { if (isset ( $maps [strtolower ( $controller )] )) { define ( 'CONTROLLER_ALIAS', strtolower ( $controller ) ); return $maps [CONTROLLER_ALIAS]; } elseif (array_search ( strtolower ( $controller ), $maps )) { return ''; } } if (C ( 'URL_CASE_INSENSITIVE' )) { $controller = ucfirst ( parse_name ( $controller, 1 ) ); } return strip_tags ( ucfirst ( $controller ) ); } static private function getAction($var) { $action = ! empty ( $_POST [$var] ) ? $_POST [$var] : (! empty ( $_GET [$var] ) ? $_GET [$var] : C ( 'DEFAULT_ACTION' )); unset ( $_POST [$var], $_GET [$var] ); if ($maps = C ( 'URL_ACTION_MAP' )) { if (isset ( $maps [strtolower ( CONTROLLER_NAME )] )) { $maps = $maps [strtolower ( CONTROLLER_NAME )]; if (isset ( $maps [strtolower ( $action )] )) { define ( 'ACTION_ALIAS', strtolower ( $action ) ); if (is_array ( $maps [ACTION_ALIAS] )) { parse_str ( $maps [ACTION_ALIAS] [1], $vars ); $_GET = array_merge ( $_GET, $vars ); return $maps [ACTION_ALIAS] [0]; } else { return $maps [ACTION_ALIAS]; } } elseif (array_search ( strtolower ( $action ), $maps )) { return ''; } } } return strip_tags ( C ( 'URL_CASE_INSENSITIVE' ) ? strtolower ( $action ) : $action ); } static private function getModule($var) { $module = (! empty ( $_GET [$var] ) ? $_GET [$var] : C ( 'DEFAULT_MODULE' )); unset ( $_GET [$var] ); if ($maps = C ( 'URL_MODULE_MAP' )) { if (isset ( $maps [strtolower ( $module )] )) { define ( 'MODULE_ALIAS', strtolower ( $module ) ); return ucfirst ( $maps [MODULE_ALIAS] ); } elseif (array_search ( strtolower ( $module ), $maps )) { return ''; } } return strip_tags ( ucfirst ( strtolower ( $module ) ) ); } }}namespace Think{ class Route { public static function check(){ $depr = C('URL_PATHINFO_DEPR'); $regx = preg_replace('/\.'.__EXT__.'$/i','',trim($_SERVER['PATH_INFO'],$depr)); if('/' != $depr){ $regx = str_replace($depr,'/',$regx); } $maps = C('URL_MAP_RULES'); if(isset($maps[$regx])) { $var = self::parseUrl($maps[$regx]); $_GET = array_merge($var, $_GET); return true; } $routes = C('URL_ROUTE_RULES'); if(!empty($routes)) { foreach ($routes as $rule=>$route){ if(is_numeric($rule)){ $rule = array_shift($route); } if(is_array($route) && isset($route[2])){ $options = $route[2]; if(isset($options['ext']) && __EXT__ != $options['ext']){ continue; } if(isset($options['method']) && REQUEST_METHOD != strtoupper($options['method'])){ continue; } if(!empty($options['callback']) && is_callable($options['callback'])) { if(false === call_user_func($options['callback'])) { continue; } } } if(0===strpos($rule,'/') && preg_match($rule,$regx,$matches)) { if($route instanceof \Closure) { $result = self::invokeRegx($route, $matches); return is_bool($result) ? $result : exit; }else{ return self::parseRegex($matches,$route,$regx); } }else{ $len1 = substr_count($regx,'/'); $len2 = substr_count($rule,'/'); if($len1>=$len2 || strpos($rule,'[')) { if('$' == substr($rule,-1,1)) { if($len1 != $len2) { continue; }else{ $rule = substr($rule,0,-1); } } $match = self::checkUrlMatch($regx,$rule); if(false !== $match) { if($route instanceof \Closure) { $result = self::invokeRule($route, $match); return is_bool($result) ? $result : exit; }else{ return self::parseRule($rule,$route,$regx); } } } } } } return false; } private static function checkUrlMatch($regx,$rule) { $m1 = explode('/',$regx); $m2 = explode('/',$rule); $var = array(); foreach ($m2 as $key=>$val){ if(0 === strpos($val,'[:')){ $val = substr($val,1,-1); } if(':' == substr($val,0,1)) { if($pos = strpos($val,'|')){ $val = substr($val,1,$pos-1); } if(strpos($val,'\\')) { $type = substr($val,-1); if('d'==$type) { if(isset($m1[$key]) && !is_numeric($m1[$key])) return false; } $name = substr($val, 1, -2); }elseif($pos = strpos($val,'^')){ $array = explode('-',substr(strstr($val,'^'),1)); if(in_array($m1[$key],$array)) { return false; } $name = substr($val, 1, $pos - 1); }else{ $name = substr($val, 1); } $var[$name] = isset($m1[$key])?$m1[$key]:''; }elseif(0 !== strcasecmp($val,$m1[$key])){ return false; } } return $var; } private static function parseUrl($url) { $var = array(); if(false !== strpos($url,'?')) { $info = parse_url($url); $path = explode('/',$info['path']); parse_str($info['query'],$var); }elseif(strpos($url,'/')){ $path = explode('/',$url); }else{ parse_str($url,$var); } if(isset($path)) { $var[C('VAR_ACTION')] = array_pop($path); if(!empty($path)) { $var[C('VAR_CONTROLLER')] = array_pop($path); } if(!empty($path)) { $var[C('VAR_MODULE')] = array_pop($path); } } return $var; } private static function parseRule($rule,$route,$regx) { $url = is_array($route)?$route[0]:$route; $paths = explode('/',$regx); $matches = array(); $rule = explode('/',$rule); foreach ($rule as $item){ $fun = ''; if(0 === strpos($item,'[:')){ $item = substr($item,1,-1); } if(0===strpos($item,':')) { if($pos = strpos($item,'|')){ $fun = substr($item,$pos+1); $item = substr($item,0,$pos); } if($pos = strpos($item,'^') ) { $var = substr($item,1,$pos-1); }elseif(strpos($item,'\\')){ $var = substr($item,1,-2); }else{ $var = substr($item,1); } $matches[$var] = !empty($fun)? $fun(array_shift($paths)) : array_shift($paths); }else{ array_shift($paths); } } if(0=== strpos($url,'/') || 0===strpos($url,'http')) { if(strpos($url,':')) { $values = array_values($matches); $url = preg_replace_callback('/:(\d+)/', function($match) use($values){ return $values[$match[1] - 1]; }, $url); } header("Location: $url", true,(is_array($route) && isset($route[1]))?$route[1]:301); exit; }else{ $var = self::parseUrl($url); $values = array_values($matches); foreach ($var as $key=>$val){ if(0===strpos($val,':')) { $var[$key] = $values[substr($val,1)-1]; } } $var = array_merge($matches,$var); if(!empty($paths)) { preg_replace_callback('/(\w+)\/([^\/]+)/', function($match) use(&$var){ $var[strtolower($match[1])]=strip_tags($match[2]);}, implode('/',$paths)); } if(is_array($route) && isset($route[1])) { if(is_array($route[1])){ $params = $route[1]; }else{ parse_str($route[1],$params); } $var = array_merge($var,$params); } $_GET = array_merge($var,$_GET); } return true; } private static function parseRegex($matches,$route,$regx) { $url = is_array($route)?$route[0]:$route; $url = preg_replace_callback('/:(\d+)/', function($match) use($matches){return $matches[$match[1]];}, $url); if(0=== strpos($url,'/') || 0===strpos($url,'http')) { header("Location: $url", true,(is_array($route) && isset($route[1]))?$route[1]:301); exit; }else{ $var = self::parseUrl($url); foreach($var as $key=>$val){ if(strpos($val,'|')){ list($val,$fun) = explode('|',$val); $var[$key] = $fun($val); } } $regx = substr_replace($regx,'',0,strlen($matches[0])); if($regx) { preg_replace_callback('/(\w+)\/([^\/]+)/', function($match) use(&$var){ $var[strtolower($match[1])] = strip_tags($match[2]); }, $regx); } if(is_array($route) && isset($route[1])) { if(is_array($route[1])){ $params = $route[1]; }else{ parse_str($route[1],$params); } $var = array_merge($var,$params); } $_GET = array_merge($var,$_GET); } return true; } static private function invokeRegx($closure, $var = array()) { $reflect = new \ReflectionFunction($closure); $params = $reflect->getParameters(); $args = array(); array_shift($var); foreach ($params as $param){ if(!empty($var)) { $args[] = array_shift($var); }elseif($param->isDefaultValueAvailable()){ $args[] = $param->getDefaultValue(); } } return $reflect->invokeArgs($args); } static private function invokeRule($closure, $var = array()) { $reflect = new \ReflectionFunction($closure); $params = $reflect->getParameters(); $args = array(); foreach ($params as $param){ $name = $param->getName(); if(isset($var[$name])) { $args[] = $var[$name]; }elseif($param->isDefaultValueAvailable()){ $args[] = $param->getDefaultValue(); } } return $reflect->invokeArgs($args); } }}namespace Think{ abstract class Controller { protected $view = null; protected $mid = 0; protected $uid = 0; protected $user = array (); protected $top_more_button = array (); protected $get_param = array (); protected $config = array (); public function __construct() { Hook::listen ( 'action_begin', $this->config ); $this->view = Think::instance ( 'Think\View' ); if (method_exists ( $this, '_initialize' )) $this->_initialize (); if (strtolower ( MODULE_NAME ) != 'install') { $this->initSite (); $this->initUser (); } } private function initSite() { $config = S ( 'DB_CONFIG_DATA' ); if (! $config) { $config = api ( 'Config/lists' ); S ( 'DB_CONFIG_DATA', $config ); } C ( $config ); if (! C ( 'WEB_SITE_CLOSE' ) && strtolower ( MODULE_NAME ) != 'admin') { $this->error ( '站点已经关闭，请稍后访问~' ); } $this->assign ( 'add_button', true ); $this->assign ( 'del_button', true ); $this->assign ( 'search_button', true ); $this->assign ( 'check_all', true ); $this->assign ( 'top_more_button', $this->top_more_button ); $diff = array ( '_addons' => 1, '_controller' => 1, '_action' => 1, 'm' => 1, 'id' => 1 ); $GLOBALS ['get_param'] = $this->get_param = array_diff_key ( $_GET, $diff ); $this->assign ( 'get_param', $this->get_param ); if (APP_DEBUG) { defined ( 'SITE_VERSION' ) or define ( 'SITE_VERSION', time () ); } else { defined ( 'SITE_VERSION' ) or define ( 'SITE_VERSION', C ( 'SYSTEM_UPDATRE_VERSION' ) ); } $this->assign ( 'system_copy_right', C ( 'COPYRIGHT' ) ); } private function initUser() { $index_1 = strtolower ( MODULE_NAME . '/*/*' ); $index_2 = strtolower ( MODULE_NAME . '/' . CONTROLLER_NAME . '/*' ); $index_3 = strtolower ( MODULE_NAME . '/' . CONTROLLER_NAME . '/' . ACTION_NAME ); $is_follow_login = session ( 'is_follow_login' ); if ($is_follow_login == 1) { return true; } $user = session ( 'user_auth' ); $user ['token'] = get_token (); $user ['openid'] = get_openid (); $access = array_map ( 'trim', explode ( "\n", C ( 'access' ) ) ); $access = array_map ( 'strtolower', $access ); $access = array_flip ( $access ); $guest_login = isset ( $access [$index_1] ) || isset ( $access [$index_2] ) || isset ( $access [$index_3] ) || $index_1 == 'admin/*/*' || $index_3 == 'home/addons/execute' || $index_2 == 'home/user/*'; if (! is_login () && ! $guest_login) { Cookie ( '__forward__', $_SERVER ['REQUEST_URI'] ); redirect ( U ( 'home/user/login' ) ); } $GLOBALS ['mid'] = $this->mid = intval ( $user ['uid'] ); $GLOBALS ['user'] = $user; $GLOBALS ['myinfo'] = get_memberinfo ( $this->mid ); $GLOBALS ['uid'] = $this->uid = intval ( $_REQUEST ['uid'] == 0 ? $this->mid : $_REQUEST ['uid'] ); $this->assign ( 'mid', $this->mid ); $this->assign ( 'uid', $this->uid ); $this->assign ( 'myinfo', $GLOBALS ['myinfo'] ); if ($this->mid) { $link = M ( 'member_public_link' )->where ( 'uid=' . $this->mid )->order ( 'is_use desc' )->select (); foreach ( $link as $l ) { $mp_ids [] = $l ['mp_id']; $is_use [$l ['mp_id']] = $l ['is_use']; } $mp_ids = getSubByKey ( $link, 'mp_id' ); if (! empty ( $mp_ids )) { $this->assign ( 'mp_ids_list', count ( $mp_ids ) ); $mp_ids = implode ( ',', $mp_ids ); $map ['id'] = array ( 'in', $mp_ids ); $member_public_list = M ( 'member_public' )->where ( $map )->order ( 'FIND_IN_SET(id,"' . $mp_ids . '")' )->select (); $member_public = $member_public_list [0]; $this->assign ( 'member_public', $member_public ); $token = get_token (); if ($member_public ['public_id'] && ($is_use [$member_public ['id']] == 0 || $token == '' || $token == - 1)) { get_token ( $member_public ['public_id'] ); } unset ( $member_public_list [0] ); $this->assign ( 'member_public_list', $member_public_list ); } else { $this->assign ( 'mp_ids_list', 0 ); } } } function initFollow($dao = false, $data = array()) { $map ['token'] = get_token (); if ($dao === false) { $public_name = M ( 'member_public' )->where ( $map )->getField ( 'public_name' ); $this->assign ( 'page_title', $public_name ); } if (is_login ()) { $token_status = D ( 'Common/AddonStatus' )->getList ( true ); if ($token_status [_ADDONS] == - 1) { $this->error ( '你没有权限管理和配置该插件' ); } return true; } $map ['openid'] = get_openid (); $user = M ( 'follow' )->where ( $map )->find (); if (! $user && ! empty ( $map ['token'] ) && $map ['token'] != '-1' && ! empty ( $map ['openid'] ) && $map ['openid'] != '-1') { D ( 'Common/Follow' )->init_follow ( $map ['openid'] ); $user = M ( 'follow' )->where ( $map )->find (); } $config = getAddonConfig ( 'UserCenter' ); $guestAccess = strtolower ( CONTROLLER_NAME ) != 'weixin'; $isWeixnLogin = ! empty ( $map ['token'] ) && ! empty ( $map ['openid'] ) && $map ['token'] != - 1 && $map ['token'] != - 1; $userNeed = ($user ['id'] > 0 && $user ['status'] < 2) || (empty ( $user ) && $guestAccess); if ($isWeixnLogin && $config ['need_bind'] == 1 && $userNeed) { $bind_url = addons_url ( 'UserCenter://UserCenter/userCenter', $map ); if ($dao === false) { if ($config ['bind_start'] != 1 && strtolower ( $_REQUEST ['_addons'] ) != 'usercenter') { Cookie ( '__forward__', $_SERVER ['REQUEST_URI'] ); redirect ( $bind_url ); } } else { if ($config ['bind_start'] != 0 && strtolower ( $data ['Event'] ) != 'subscribe') { $dao->replyText ( '请先<a href="' . $bind_url . '">绑定账号</a>再使用' ); exit (); } } } if (! $user) { $user ['status'] = 0; $user ['id'] = session ( 'mid' ); if (! $user ['id']) { $youke_uid = M ( 'config' )->where ( 'name="FOLLOW_YOUKE_UID"' )->getField ( 'value' ) - 1; $user ['id'] = $youke_uid; M ( 'config' )->where ( 'name="FOLLOW_YOUKE_UID"' )->setField ( 'value', $youke_uid ); } } $user ['uid'] = $user ['id']; $GLOBALS ['mid'] = $this->mid = intval ( $user ['uid'] ); $GLOBALS ['user'] = $user; $GLOBALS ['uid'] = $this->uid = intval ( $_REQUEST ['uid'] == 0 ? $this->mid : $_REQUEST ['uid'] ); $this->assign ( 'mid', $this->mid ); $this->assign ( 'uid', $this->uid ); session ( 'mid', $this->mid ); session ( 'is_follow_login', 1 ); } protected function display($templateFile = '', $charset = '', $contentType = '', $content = '', $prefix = '') { $this->view->display ( $templateFile, $charset, $contentType, $content, $prefix ); } protected function show($content, $charset = '', $contentType = '', $prefix = '') { $this->view->display ( '', $charset, $contentType, $content, $prefix ); } protected function fetch($templateFile = '', $content = '', $prefix = '') { return $this->view->fetch ( $templateFile, $content, $prefix ); } protected function buildHtml($htmlfile = '', $htmlpath = '', $templateFile = '') { $content = $this->fetch ( $templateFile ); $htmlpath = ! empty ( $htmlpath ) ? $htmlpath : HTML_PATH; $htmlfile = $htmlpath . $htmlfile . C ( 'HTML_FILE_SUFFIX' ); Storage::put ( $htmlfile, $content, 'html' ); return $content; } protected function theme($theme) { $this->view->theme ( $theme ); return $this; } protected function assign($name, $value = '') { $this->view->assign ( $name, $value ); return $this; } public function __set($name, $value) { $this->assign ( $name, $value ); } public function get($name = '') { return $this->view->get ( $name ); } public function __get($name) { return $this->get ( $name ); } public function __isset($name) { return $this->get ( $name ); } public function __call($method, $args) { if (0 === strcasecmp ( $method, ACTION_NAME . C ( 'ACTION_SUFFIX' ) )) { if (method_exists ( $this, '_empty' )) { $this->_empty ( $method, $args ); } elseif (file_exists_case ( $this->view->parseTemplate () )) { $this->display (); } else { E ( L ( '_ERROR_ACTION_' ) . ':' . ACTION_NAME ); } } else { E ( __CLASS__ . ':' . $method . L ( '_METHOD_NOT_EXIST_' ) ); return; } } protected function error($message = '', $jumpUrl = '', $ajax = false) { $this->dispatchJump ( $message, 0, $jumpUrl, $ajax ); } protected function success($message = '', $jumpUrl = '', $ajax = false) { $this->dispatchJump ( $message, 1, $jumpUrl, $ajax ); } protected function ajaxReturn($data, $type = '') { if (empty ( $type )) $type = C ( 'DEFAULT_AJAX_RETURN' ); switch (strtoupper ( $type )) { case 'JSON' : header ( 'Content-Type:application/json; charset=utf-8' ); exit ( json_encode ( $data ) ); case 'XML' : header ( 'Content-Type:text/xml; charset=utf-8' ); exit ( xml_encode ( $data ) ); case 'JSONP' : header ( 'Content-Type:application/json; charset=utf-8' ); $handler = isset ( $_GET [C ( 'VAR_JSONP_HANDLER' )] ) ? $_GET [C ( 'VAR_JSONP_HANDLER' )] : C ( 'DEFAULT_JSONP_HANDLER' ); exit ( $handler . '(' . json_encode ( $data ) . ');' ); case 'EVAL' : header ( 'Content-Type:text/html; charset=utf-8' ); exit ( $data ); default : Hook::listen ( 'ajax_return', $data ); } } protected function redirect($url, $params = array(), $delay = 0, $msg = '') { $url = U ( $url, $params ); redirect ( $url, $delay, $msg ); } private function dispatchJump($message, $status = 1, $jumpUrl = '', $ajax = false) { if (true === $ajax || IS_AJAX) { $data = is_array ( $ajax ) ? $ajax : array (); $data ['info'] = $message; $data ['status'] = $status; $data ['url'] = $jumpUrl; $this->ajaxReturn ( $data ); } if (is_int ( $ajax )) $this->assign ( 'waitSecond', $ajax ); if (! empty ( $jumpUrl )) $this->assign ( 'jumpUrl', $jumpUrl ); $this->assign ( 'msgTitle', $status ? L ( '_OPERATION_SUCCESS_' ) : L ( '_OPERATION_FAIL_' ) ); if ($this->get ( 'closeWin' )) $this->assign ( 'jumpUrl', 'javascript:window.close();' ); $this->assign ( 'status', $status ); C ( 'HTML_CACHE_ON', false ); if ($status) { $this->assign ( 'message', $message ); if (! isset ( $this->waitSecond )) $this->assign ( 'waitSecond', '1' ); if (! isset ( $this->jumpUrl )) $this->assign ( "jumpUrl", $_SERVER ["HTTP_REFERER"] ); $this->display ( C ( 'TMPL_ACTION_SUCCESS' ) ); } else { $this->assign ( 'error', $message ); if (! isset ( $this->waitSecond )) $this->assign ( 'waitSecond', '3' ); if (! isset ( $this->jumpUrl )) $this->assign ( 'jumpUrl', "javascript:history.back(-1);" ); $this->display ( C ( 'TMPL_ACTION_ERROR' ) ); } exit (); } public function outExcel($dataArr, $fileName = '', $sheet = false) { require_once VENDOR_PATH . 'download-xlsx.php'; export_csv ( $dataArr, $fileName, $sheet ); unset ( $sheet ); unset ( $dataArr ); } public function inExcel() { require_once VENDOR_PATH . '/PHPExcel.php'; require_once VENDOR_PATH . 'PHPExcel/IOFactory.php'; require_once VENDOR_PATH . 'PHPExcel/Reader/Excel5.php'; } public function __destruct() { Hook::listen ( 'action_end' ); } public function getModel($model = null) { $model || $model = $_REQUEST ['_addons']; $model || $model = $_REQUEST ['model']; $model || $this->error ( '模型名标识必须！' ); if (is_numeric ( $model )) { $model = M ( 'Model' )->find ( $model ); } else { $model = M ( 'Model' )->getByName ( $model ); } $this->assign ( 'model', $model ); return $model; } public function common_lists($model = null, $page = 0, $templateFile = '', $order = 'id desc') { is_array ( $model ) || $model = $this->getModel ( $model ); $list_data = $this->_get_model_list ( $model, $page, $order ); $this->assign ( $list_data ); $templateFile || $templateFile = $model ['template_list'] ? $model ['template_list'] : ''; $this->display ( $templateFile ); } public function common_del($model = null, $ids = null) { is_array ( $model ) || $model = $this->getModel ( $model ); ! empty ( $ids ) || $ids = I ( 'id' ); ! empty ( $ids ) || $ids = array_filter ( array_unique ( ( array ) I ( 'ids', 0 ) ) ); ! empty ( $ids ) || $this->error ( '请选择要操作的数据!' ); $Model = M ( get_table_name ( $model ['id'] ) ); $map ['id'] = array ( 'in', $ids ); $token = get_token (); if (defined ( 'ADDON_PUBLIC_PATH' ) && ! empty ( $token )) { $map ['token'] = $token; } if ($Model->where ( $map )->delete ()) { $this->success ( '删除成功' ); } else { $this->error ( '删除失败！' ); } } public function common_edit($model = null, $id = 0, $templateFile = '') { is_array ( $model ) || $model = $this->getModel ( $model ); $id || $id = I ( 'id' ); $data = M ( get_table_name ( $model ['id'] ) )->find ( $id ); $data || $this->error ( '数据不存在！' ); $token = get_token (); if (isset ( $data ['token'] ) && $token != $data ['token'] && defined ( 'ADDON_PUBLIC_PATH' )) { $this->error ( '非法访问！' ); } if (IS_POST) { $Model = D ( parse_name ( get_table_name ( $model ['id'] ), 1 ) ); $Model = $this->checkAttr ( $Model, $model ['id'] ); if ($Model->create () && $Model->save ()) { $this->_saveKeyword ( $model, $id ); $this->success ( '保存' . $model ['title'] . '成功！', U ( 'lists?model=' . $model ['name'], $this->get_param ) ); } else { $this->error ( $Model->getError () ); } } else { $fields = get_model_attribute ( $model ['id'] ); $this->assign ( 'fields', $fields ); $this->assign ( 'data', $data ); $this->meta_title = '编辑' . $model ['title']; $templateFile || $templateFile = $model ['template_edit'] ? $model ['template_edit'] : ''; $this->display ( $templateFile ); } } public function common_add($model = null, $templateFile = '') { is_array ( $model ) || $model = $this->getModel ( $model ); if (IS_POST) { $Model = D ( parse_name ( get_table_name ( $model ['id'] ), 1 ) ); $Model = $this->checkAttr ( $Model, $model ['id'] ); if ($Model->create () && $id = $Model->add ()) { $this->_saveKeyword ( $model, $id ); $this->success ( '添加' . $model ['title'] . '成功！', U ( 'lists?model=' . $model ['name'], $this->get_param ) ); } else { $this->error ( $Model->getError () ); } } else { $fields = get_model_attribute ( $model ['id'] ); $this->assign ( 'fields', $fields ); $this->meta_title = '新增' . $model ['title']; $templateFile || $templateFile = $model ['template_add'] ? $model ['template_add'] : ''; $this->display ( $templateFile ); } } public function _saveKeyword($model, $id) { if (isset ( $_POST ['keyword'] ) && $model ['name'] != 'keyword' && defined ( '_ADDONS' ) && ! isset ( $_REQUEST ['keyword_no_deal'] )) { D ( 'Common/Keyword' )->set ( $_POST ['keyword'], _ADDONS, $id, $_POST ['keyword_type'] ); } } protected function checkAttr($Model, $model_id) { $fields = get_model_attribute ( $model_id, false ); $validate = $auto = array (); foreach ( $fields as $key => $attr ) { if ($attr ['is_must']) { $validate [] = array ( $attr ['name'], 'require', $attr ['title'] . '必须!' ); } if (! empty ( $attr ['validate_rule'] ) || $attr ['validate_type'] == 'unique') { $validate [] = array ( $attr ['name'], $attr ['validate_rule'], $attr ['error_info'] ? $attr ['error_info'] : $attr ['title'] . '验证错误', 0, $attr ['validate_type'], $attr ['validate_time'] ); } if (! empty ( $attr ['auto_rule'] )) { $auto [] = array ( $attr ['name'], $attr ['auto_rule'], $attr ['auto_time'], $attr ['auto_type'] ); } elseif ('checkbox' == $attr ['type']) { $auto [] = array ( $attr ['name'], 'arr2str', 3, 'function' ); } elseif ('datetime' == $attr ['type']) { $auto [] = array ( $attr ['name'], 'strtotime', 3, 'function' ); } elseif ('date' == $attr ['type']) { $auto [] = array ( $attr ['name'], 'strtotime', 3, 'function' ); } } return $Model->validate ( $validate )->auto ( $auto ); } public function _get_model_list($model = null, $page = 0, $order = 'id desc') { $page || $page = I ( 'p', 1, 'intval' ); $list_data = $this->_list_grid ( $model ); $grids = $list_data ['list_grids']; $fields = $list_data ['fields']; $map = $this->_search_map ( $model, $fields ); $row = empty ( $model ['list_row'] ) ? 20 : $model ['list_row']; if ($model ['extend']) { $name = get_table_name ( $model ['id'] ); $parent = get_table_name ( $model ['extend'] ); $fix = C ( "DB_PREFIX" ); $key = array_search ( 'id', $fields ); if (false === $key) { array_push ( $fields, "{$fix}{$parent}.id as id" ); } else { $fields [$key] = "{$fix}{$parent}.id as id"; } $count = M ( $parent )->join ( "INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id" )->where ( $map )->count (); $data = M ( $parent )->join ( "INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id" )->field ( empty ( $fields ) ? true : $fields )->where ( $map )->order ( "{$fix}{$parent}.{$order}" )->page ( $page, $row )->select (); } else { empty ( $fields ) || in_array ( 'id', $fields ) || array_push ( $fields, 'id' ); $name = parse_name ( get_table_name ( $model ['id'] ), true ); $data = M ( $name )->field ( empty ( $fields ) ? true : $fields )->where ( $map )->order ( $order )->page ( $page, $row )->select (); $count = M ( $name )->where ( $map )->count (); } $list_data ['list_data'] = $data; if ($count > $row) { $page = new \Think\Page ( $count, $row ); $page->setConfig ( 'theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%' ); $list_data ['_page'] = $page->show (); } return $list_data; } public function _list_grid($model) { $fields = array (); $grids = preg_split ( '/[;\r\n]+/s', htmlspecialchars_decode ( $model ['list_grid'] ) ); foreach ( $grids as &$value ) { $val = explode ( ':', $value ); $field = explode ( ',', $val [0] ); $value = array ( 'field' => $field, 'title' => $val [1] ); if (preg_match ( '/^([0-9]*)%/', $val [1], $matches )) { $value ['title'] = str_replace ( $matches [0], '', $value ['title'] ); $value ['width'] = $matches [1]; } if (isset ( $val [2] )) { $value ['href'] = $val [2]; preg_replace_callback ( '/\[([a-z_]+)\]/', function ($match) use(&$fields) { $fields [] = $match [1]; }, $value ['href'] ); } if (strpos ( $val [1], '|' )) { list ( $value ['title'], $value ['format'] ) = explode ( '|', $val [1] ); } foreach ( $field as $val ) { $array = explode ( '|', $val ); $fields [] = $array [0]; } } $model_fields = M ( 'attribute' )->where ( 'model_id=' . $model ['id'] )->field ( 'name' )->select (); $model_fields = getSubByKey ( $model_fields, 'name' ); in_array ( 'id', $model_fields ) || array_push ( $model_fields, 'id' ); $fields = array_intersect ( $fields, $model_fields ); $res ['fields'] = array_unique ( $fields ); $res ['list_grids'] = $grids; return $res; } public function _search_map($model, $fields) { $map = array (); $token = get_token (); if (defined ( 'ADDON_PUBLIC_PATH' ) && ! empty ( $token )) { $map ['token'] = $token; } $conditon = session ( 'common_condition' ); if (! empty ( $conditon )) { $map = array_merge ( $map, $conditon ); } session ( 'common_condition', null ); $key = $model ['search_key'] ? $model ['search_key'] : 'title'; $keyArr = explode ( ':', $key ); $key = $keyArr [0]; $placeholder = isset ( $keyArr [1] ) ? $keyArr [1] : '请输入关键字'; $this->assign ( 'placeholder', $placeholder ); $this->assign ( 'search_key', $key ); if (isset ( $_REQUEST [$key] ) && ! isset ( $map [$key] )) { $map [$key] = array ( 'like', '%' . htmlspecialchars ( $_REQUEST [$key] ) . '%' ); unset ( $_REQUEST [$key] ); } foreach ( $_REQUEST as $name => $val ) { if (! isset ( $map [$name] ) && in_array ( $name, $fields )) { $map [$name] = $val; } } return $map; } } class_alias ( 'Think\Controller', 'Think\Action' );}namespace Think{ class View { protected $tVar = array(); protected $theme = ''; public function assign($name,$value=''){ if(is_array($name)) { $this->tVar = array_merge($this->tVar,$name); }else { $this->tVar[$name] = $value; } } public function get($name=''){ if('' === $name) { return $this->tVar; } return isset($this->tVar[$name])?$this->tVar[$name]:false; } public function display($templateFile='',$charset='',$contentType='',$content='',$prefix='') { G('viewStartTime'); Hook::listen('view_begin',$templateFile); $content = $this->fetch($templateFile,$content,$prefix); $this->render($content,$charset,$contentType); Hook::listen('view_end'); } private function render($content,$charset='',$contentType=''){ if(empty($charset)) $charset = C('DEFAULT_CHARSET'); if(empty($contentType)) $contentType = C('TMPL_CONTENT_TYPE'); header('Content-Type:'.$contentType.'; charset='.$charset); header('Cache-control: '.C('HTTP_CACHE_CONTROL')); header('X-Powered-By:ThinkPHP'); echo $content; } public function fetch($templateFile='',$content='',$prefix='') { if(empty($content)) { $templateFile = $this->parseTemplate($templateFile); if(!is_file($templateFile)) E(L('_TEMPLATE_NOT_EXIST_').':'.$templateFile); } ob_start(); ob_implicit_flush(0); if('php' == strtolower(C('TMPL_ENGINE_TYPE'))) { extract($this->tVar, EXTR_OVERWRITE); empty($content)?include $templateFile:eval('?>'.$content); }else{ $params = array('var'=>$this->tVar,'file'=>$templateFile,'content'=>$content,'prefix'=>$prefix); Hook::listen('view_parse',$params); } $content = ob_get_clean(); Hook::listen('view_filter',$content); return $content; } public function parseTemplate($template='') { if(is_file($template)) { return $template; } $depr = C('TMPL_FILE_DEPR'); $template = str_replace(':', $depr, $template); $theme = $this->getTemplateTheme(); $module = MODULE_NAME; if(strpos($template,'@')){ list($module,$template) = explode('@',$template); } if(!defined('THEME_PATH')){ if(C('VIEW_PATH')){ define('THEME_PATH', C('VIEW_PATH').$module.'/'.$theme); }else{ define('THEME_PATH', APP_PATH.$module.'/'.C('DEFAULT_V_LAYER').'/'.$theme); } } if('' == $template) { $template = CONTROLLER_NAME . $depr . ACTION_NAME; }elseif(false === strpos($template, $depr)){ $template = CONTROLLER_NAME . $depr . $template; } $file = THEME_PATH.$template.C('TMPL_TEMPLATE_SUFFIX'); if(C('TMPL_LOAD_DEFAULTTHEME') && THEME_NAME != C('DEFAULT_THEME') && !is_file($file)){ $file = dirname(THEME_PATH).'/'.C('DEFAULT_THEME').'/'.$template.C('TMPL_TEMPLATE_SUFFIX'); } return $file; } public function theme($theme){ $this->theme = $theme; return $this; } private function getTemplateTheme() { if($this->theme) { $theme = $this->theme; }else{ $theme = C('DEFAULT_THEME'); if(C('TMPL_DETECT_THEME')) { $t = C('VAR_TEMPLATE'); if (isset($_GET[$t])){ $theme = $_GET[$t]; }elseif(cookie('think_template')){ $theme = cookie('think_template'); } if(!in_array($theme,explode(',',C('THEME_LIST')))){ $theme = C('DEFAULT_THEME'); } cookie('think_template',$theme,864000); } } defined('THEME_NAME') || define('THEME_NAME', $theme); return $theme?$theme . '/':''; } }}namespace Think{ abstract class Behavior { protected $options = array(); public function __construct() { if(!empty($this->options)) { foreach ($this->options as $name=>$val){ if(NULL !== C($name)) { $this->options[$name] = C($name); }else{ C($name,$val); } } array_change_key_case($this->options); } } public function __get($name){ return $this->options[strtolower($name)]; } abstract public function run(&$params); }}namespace Behavior{ use Think\Behavior; use Think\Storage; defined('THINK_PATH') or exit(); class ReadHtmlCacheBehavior extends Behavior { protected $options = array( 'HTML_CACHE_ON' => false, 'HTML_CACHE_TIME' => 60, 'HTML_CACHE_RULES' => array(), 'HTML_FILE_SUFFIX' => '.html', ); public function run(&$params){ if(IS_GET && C('HTML_CACHE_ON')) { $cacheTime = $this->requireHtmlCache(); if( false !== $cacheTime && $this->checkHTMLCache(HTML_FILE_NAME,$cacheTime)) { echo Storage::read(HTML_FILE_NAME,'html'); exit(); } } } static private function requireHtmlCache() { $htmls = C('HTML_CACHE_RULES'); if(!empty($htmls)) { $htmls = array_change_key_case($htmls); $controllerName = strtolower(CONTROLLER_NAME); $actionName = strtolower(ACTION_NAME); if(isset($htmls[$controllerName.':'.$actionName])) { $html = $htmls[$controllerName.':'.$actionName]; }elseif(isset($htmls[$controllerName.':'])){ $html = $htmls[$controllerName.':']; }elseif(isset($htmls[$actionName])){ $html = $htmls[$actionName]; }elseif(isset($htmls['*'])){ $html = $htmls['*']; } if(!empty($html)) { $rule = is_array($html)?$html[0]:$html; $callback = function($match){ switch($match[1]){ case '_GET': $var = $_GET[$match[2]]; break; case '_POST': $var = $_POST[$match[2]]; break; case '_REQUEST': $var = $_REQUEST[$match[2]]; break; case '_SERVER': $var = $_SERVER[$match[2]]; break; case '_SESSION': $var = $_SESSION[$match[2]]; break; case '_COOKIE': $var = $_COOKIE[$match[2]]; break; } return (count($match) == 4) ? $match[3]($var) : $var; }; $rule = preg_replace_callback('/{\$(_\w+)\.(\w+)(?:\|(\w+))?}/', $callback, $rule); $rule = preg_replace_callback('/{(\w+)\|(\w+)}/', function($match){return $match[2]($_GET[$match[1]]);}, $rule); $rule = preg_replace_callback('/{(\w+)}/', function($match){return $_GET[$match[1]];}, $rule); $rule = str_ireplace( array('{:controller}','{:action}','{:module}'), array(CONTROLLER_NAME,ACTION_NAME,MODULE_NAME), $rule); $rule = preg_replace_callback('/{|(\w+)}/', function($match){return $match[1]();},$rule); $cacheTime = C('HTML_CACHE_TIME',null,60); if(is_array($html)){ if(!empty($html[2])) $rule = $html[2]($rule); $cacheTime = isset($html[1])?$html[1]:$cacheTime; }else{ $cacheTime = $cacheTime; } define('HTML_FILE_NAME',HTML_PATH . $rule.C('HTML_FILE_SUFFIX',null,'.html')); return $cacheTime; } } return false; } static public function checkHTMLCache($cacheFile='',$cacheTime='') { if(!is_file($cacheFile) && 'sae' != APP_MODE ){ return false; }elseif (filemtime(C('TEMPLATE_NAME')) > Storage::get($cacheFile,'mtime','html')) { return false; }elseif(!is_numeric($cacheTime) && function_exists($cacheTime)){ return $cacheTime($cacheFile); }elseif ($cacheTime != 0 && NOW_TIME > Storage::get($cacheFile,'mtime','html')+$cacheTime) { return false; } return true; } }}namespace Behavior{ use Think\Behavior; use Think\Log; defined('THINK_PATH') or exit(); class ShowPageTraceBehavior extends Behavior { protected $options = array( 'SHOW_PAGE_TRACE' => false, 'TRACE_PAGE_TABS' => array('BASE'=>'基本','FILE'=>'文件','INFO'=>'流程','ERR|NOTIC'=>'错误','SQL'=>'SQL','DEBUG'=>'调试'), 'PAGE_TRACE_SAVE' => false, ); public function run(&$params){ if(!IS_AJAX && !IS_CLI && C('SHOW_PAGE_TRACE')) { echo $this->showTrace(); } } private function showTrace() { $files = get_included_files(); $info = array(); foreach ($files as $key=>$file){ $info[] = $file.' ( '.number_format(filesize($file)/1024,2).' KB )'; } $trace = array(); $base = array( '请求信息' => date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']).' '.$_SERVER['SERVER_PROTOCOL'].' '.$_SERVER['REQUEST_METHOD'].' : '.__SELF__, '运行时间' => $this->showTime(), '吞吐率' => number_format(1/G('beginTime','viewEndTime'),2).'req/s', '内存开销' => MEMORY_LIMIT_ON?number_format((memory_get_usage() - $GLOBALS['_startUseMems'])/1024,2).' kb':'不支持', '查询信息' => N('db_query').' queries '.N('db_write').' writes ', '文件加载' => count(get_included_files()), '缓存信息' => N('cache_read').' gets '.N('cache_write').' writes ', '配置加载' => count(c()), '会话信息' => 'SESSION_ID='.session_id(), ); $traceFile = COMMON_PATH.'Conf/trace.php'; if(is_file($traceFile)) { $base = array_merge($base,include $traceFile); } $debug = trace(); $tabs = C('TRACE_PAGE_TABS'); foreach ($tabs as $name=>$title){ switch(strtoupper($name)) { case 'BASE': $trace[$title] = $base; break; case 'FILE': $trace[$title] = $info; break; default: $name = strtoupper($name); if(strpos($name,'|')) { $names = explode('|',$name); $result = array(); foreach($names as $name){ $result += isset($debug[$name])?$debug[$name]:array(); } $trace[$title] = $result; }else{ $trace[$title] = isset($debug[$name])?$debug[$name]:''; } } } if($save = C('PAGE_TRACE_SAVE')) { if(is_array($save)) { $tabs = C('TRACE_PAGE_TABS',null,$this->tracePageTabs); $array = array(); foreach ($save as $tab){ $array[] = $tabs[$tab]; } } $content = date('[ c ]').' '.get_client_ip().' '.$_SERVER['REQUEST_URI']."\r\n"; foreach ($trace as $key=>$val){ if(!isset($array) || in_array_case($key,$array)) { $content .= '[ '.$key." ]\r\n"; if(is_array($val)) { foreach ($val as $k=>$v){ $content .= (!is_numeric($k)?$k.':':'').print_r($v,true)."\r\n"; } }else{ $content .= print_r($val,true)."\r\n"; } $content .= "\r\n"; } } error_log(str_replace('<br/>',"\r\n",$content), 3,C('LOG_PATH').date('y_m_d').'_trace.log'); } unset($files,$info,$base); ob_start(); include C('TMPL_TRACE_FILE')?C('TMPL_TRACE_FILE'):THINK_PATH.'Tpl/page_trace.tpl'; return ob_get_clean(); } private function showTime() { G('beginTime',$GLOBALS['_beginTime']); G('viewEndTime'); return G('beginTime','viewEndTime').'s ( Load:'.G('beginTime','loadTime').'s Init:'.G('loadTime','initTime').'s Exec:'.G('initTime','viewStartTime').'s Template:'.G('viewStartTime','viewEndTime').'s )'; } }}namespace Behavior{ use Think\Behavior; use Think\Storage; use Think\Think; defined('THINK_PATH') or exit(); class ParseTemplateBehavior extends Behavior { protected $options = array( 'TMPL_ENGINE_TYPE' => 'Think', 'TMPL_CACHFILE_SUFFIX' => '.php', 'TMPL_DENY_FUNC_LIST' => 'echo,exit', 'TMPL_DENY_PHP' => false, 'TMPL_L_DELIM' => '{', 'TMPL_R_DELIM' => '}', 'TMPL_VAR_IDENTIFY' => 'array', 'TMPL_STRIP_SPACE' => true, 'TMPL_CACHE_ON' => true, 'TMPL_CACHE_PREFIX' => '', 'TMPL_CACHE_TIME' => 0, 'TMPL_LAYOUT_ITEM' => '{__CONTENT__}', 'LAYOUT_ON' => false, 'LAYOUT_NAME' => 'layout', 'TAGLIB_BEGIN' => '<', 'TAGLIB_END' => '>', 'TAGLIB_LOAD' => true, 'TAGLIB_BUILD_IN' => 'cx', 'TAGLIB_PRE_LOAD' => '', ); public function run(&$_data){ $engine = strtolower(C('TMPL_ENGINE_TYPE')); $_content = empty($_data['content'])?$_data['file']:$_data['content']; $_data['prefix'] = !empty($_data['prefix'])?$_data['prefix']:C('TMPL_CACHE_PREFIX'); if('think'==$engine){ if((!empty($_data['content']) && $this->checkContentCache($_data['content'],$_data['prefix'])) || $this->checkCache($_data['file'],$_data['prefix'])) { Storage::load(C('CACHE_PATH').$_data['prefix'].md5($_content).C('TMPL_CACHFILE_SUFFIX'),$_data['var'],'tpl'); }else{ $tpl = Think::instance('Think\\Template'); $tpl->fetch($_content,$_data['var'],$_data['prefix']); } }else{ if(strpos($engine,'\\')){ $class = $engine; }else{ $class = 'Think\\Template\\Driver\\'.ucwords($engine); } if(class_exists($class)) { $tpl = new $class; $tpl->fetch($_content,$_data['var']); }else { E(L('_NOT_SUPPORT_').': ' . $class); } } } protected function checkCache($tmplTemplateFile,$prefix='') { if (!C('TMPL_CACHE_ON')) return false; $tmplCacheFile = C('CACHE_PATH').$prefix.md5($tmplTemplateFile).C('TMPL_CACHFILE_SUFFIX'); if(!Storage::has($tmplCacheFile,'tpl')){ return false; }elseif (filemtime($tmplTemplateFile) > Storage::get($tmplCacheFile,'mtime','tpl')) { return false; }elseif (C('TMPL_CACHE_TIME') != 0 && time() > Storage::get($tmplCacheFile,'mtime','tpl')+C('TMPL_CACHE_TIME')) { return false; } if(C('LAYOUT_ON')) { $layoutFile = THEME_PATH.C('LAYOUT_NAME').C('TMPL_TEMPLATE_SUFFIX'); if(filemtime($layoutFile) > Storage::get($tmplCacheFile,'mtime','tpl')) { return false; } } return true; } protected function checkContentCache($tmplContent,$prefix='') { if(Storage::has(C('CACHE_PATH').$prefix.md5($tmplContent).C('TMPL_CACHFILE_SUFFIX'),'tpl')){ return true; }else{ return false; } } }}namespace Behavior{ use Think\Behavior; defined('THINK_PATH') or exit(); class ContentReplaceBehavior extends Behavior { protected $options = array( 'TMPL_PARSE_STRING' => array(), ); public function run(&$content){ $content = $this->templateContentReplace($content); } protected function templateContentReplace($content) { $replace = array( '__ROOT__' => __ROOT__, '__APP__' => __APP__, '__MODULE__' => __MODULE__, '__ACTION__' => __ACTION__, '__SELF__' => __SELF__, '__CONTROLLER__'=> __CONTROLLER__, '__URL__' => __CONTROLLER__, '__PUBLIC__' => __ROOT__.'/Public', ); if(is_array(C('TMPL_PARSE_STRING')) ) $replace = array_merge($replace,C('TMPL_PARSE_STRING')); $content = str_replace(array_keys($replace),array_values($replace),$content); return $content; } }}namespace Behavior{ use Think\Behavior; use Think\Storage; defined('THINK_PATH') or exit(); class WriteHtmlCacheBehavior extends Behavior { public function run(&$content){ if(C('HTML_CACHE_ON') && defined('HTML_FILE_NAME')) { Storage::put(HTML_FILE_NAME , $content,'html'); } } }} namespace { Think\Think::addMap(array ( 'Think\\Log' => 'D:\\www\\wxjw\\ThinkPHP\\Library/Think/Log.class.php', 'Think\\Log\\Driver\\File' => 'D:\\www\\wxjw\\ThinkPHP\\Library/Think/Log/Driver/File.class.php', 'Think\\Exception' => 'D:\\www\\wxjw\\ThinkPHP\\Library/Think/Exception.class.php', 'Think\\Model' => 'D:\\www\\wxjw\\ThinkPHP\\Library/Think/Model.class.php', 'Think\\Db' => 'D:\\www\\wxjw\\ThinkPHP\\Library/Think/Db.class.php', 'Think\\Template' => 'D:\\www\\wxjw\\ThinkPHP\\Library/Think/Template.class.php', 'Think\\Cache' => 'D:\\www\\wxjw\\ThinkPHP\\Library/Think/Cache.class.php', 'Think\\Cache\\Driver\\File' => 'D:\\www\\wxjw\\ThinkPHP\\Library/Think/Cache/Driver/File.class.php', 'Think\\Storage' => 'D:\\www\\wxjw\\ThinkPHP\\Library/Think/Storage.class.php', )); L(array ( '_MODULE_NOT_EXIST_' => '无法加载模块', '_CONTROLLER_NOT_EXIST_' => '无法加载控制器', '_ERROR_ACTION_' => '非法操作', '_LANGUAGE_NOT_LOAD_' => '无法加载语言包', '_TEMPLATE_NOT_EXIST_' => '模板不存在', '_MODULE_' => '模块', '_ACTION_' => '操作', '_MODEL_NOT_EXIST_' => '模型不存在或者没有定义', '_VALID_ACCESS_' => '没有权限', '_XML_TAG_ERROR_' => 'XML标签语法错误', '_DATA_TYPE_INVALID_' => '非法数据对象！', '_OPERATION_WRONG_' => '操作出现错误', '_NOT_LOAD_DB_' => '无法加载数据库', '_NO_DB_DRIVER_' => '无法加载数据库驱动', '_NOT_SUPPORT_DB_' => '系统暂时不支持数据库', '_NO_DB_CONFIG_' => '没有定义数据库配置', '_NOT_SUPPORT_' => '系统不支持', '_CACHE_TYPE_INVALID_' => '无法加载缓存类型', '_FILE_NOT_WRITABLE_' => '目录（文件）不可写', '_METHOD_NOT_EXIST_' => '方法不存在！', '_CLASS_NOT_EXIST_' => '实例化一个不存在的类！', '_CLASS_CONFLICT_' => '类名冲突', '_TEMPLATE_ERROR_' => '模板引擎错误', '_CACHE_WRITE_ERROR_' => '缓存文件写入失败！', '_TAGLIB_NOT_EXIST_' => '标签库未定义', '_OPERATION_FAIL_' => '操作失败！', '_OPERATION_SUCCESS_' => '操作成功！', '_SELECT_NOT_EXIST_' => '记录不存在！', '_EXPRESS_ERROR_' => '表达式错误', '_TOKEN_ERROR_' => '表单令牌错误', '_RECORD_HAS_UPDATE_' => '记录已经更新', '_NOT_ALLOW_PHP_' => '模板禁用PHP代码', '_PARAM_ERROR_' => '参数错误或者未定义', '_ERROR_QUERY_EXPRESS_' => '错误的查询条件', )); C(array ( 'APP_FILE_CASE' => false, 'APP_SUB_DOMAIN_DEPLOY' => false, 'APP_SUB_DOMAIN_RULES' => array ( ), 'APP_DOMAIN_SUFFIX' => '', 'ACTION_SUFFIX' => '', 'MULTI_MODULE' => true, 'MODULE_DENY_LIST' => array ( 0 => 'Common', 1 => 'User', ), 'CONTROLLER_LEVEL' => 1, 'COOKIE_EXPIRE' => 0, 'COOKIE_DOMAIN' => '', 'COOKIE_PATH' => '/', 'COOKIE_PREFIX' => '', 'DEFAULT_M_LAYER' => 'Model', 'DEFAULT_C_LAYER' => 'Controller', 'DEFAULT_V_LAYER' => 'View', 'DEFAULT_LANG' => 'zh-cn', 'DEFAULT_THEME' => '', 'DEFAULT_MODULE' => 'Home', 'DEFAULT_CONTROLLER' => 'Index', 'DEFAULT_ACTION' => 'index', 'DEFAULT_CHARSET' => 'utf-8', 'DEFAULT_TIMEZONE' => 'PRC', 'DEFAULT_AJAX_RETURN' => 'JSON', 'DEFAULT_JSONP_HANDLER' => 'jsonpReturn', 'DEFAULT_FILTER' => 'safe', 'DB_TYPE' => 'mysql', 'DB_HOST' => '192.168.103.101', 'DB_NAME' => 'wxjw', 'DB_USER' => 'root', 'DB_PWD' => '18587733312', 'DB_PORT' => '3306', 'DB_PREFIX' => 'wp_', 'DB_FIELDTYPE_CHECK' => false, 'DB_FIELDS_CACHE' => true, 'DB_CHARSET' => 'utf8', 'DB_DEPLOY_TYPE' => 0, 'DB_RW_SEPARATE' => false, 'DB_MASTER_NUM' => 1, 'DB_SLAVE_NO' => '', 'DB_SQL_BUILD_CACHE' => false, 'DB_SQL_BUILD_QUEUE' => 'file', 'DB_SQL_BUILD_LENGTH' => 20, 'DB_SQL_LOG' => false, 'DB_BIND_PARAM' => false, 'DATA_CACHE_TIME' => 0, 'DATA_CACHE_COMPRESS' => false, 'DATA_CACHE_CHECK' => false, 'DATA_CACHE_PREFIX' => '', 'DATA_CACHE_TYPE' => 'File', 'DATA_CACHE_PATH' => './Runtime/Temp/', 'DATA_CACHE_SUBDIR' => false, 'DATA_PATH_LEVEL' => 1, 'ERROR_MESSAGE' => '页面错误！请稍后再试～', 'ERROR_PAGE' => '', 'SHOW_ERROR_MSG' => false, 'TRACE_EXCEPTION' => false, 'TRACE_MAX_RECORD' => 100, 'LOG_RECORD' => false, 'LOG_TYPE' => 'File', 'LOG_LEVEL' => 'EMERG,ALERT,CRIT,ERR', 'LOG_FILE_SIZE' => 2097152, 'LOG_EXCEPTION_RECORD' => false, 'SESSION_AUTO_START' => true, 'SESSION_OPTIONS' => array ( ), 'SESSION_TYPE' => '', 'SESSION_PREFIX' => '', 'TMPL_CONTENT_TYPE' => 'text/html', 'TMPL_ACTION_ERROR' => 'D:\\www\\wxjw\\ThinkPHP/../Application/Home/View/default/dispatch_jump.html', 'TMPL_ACTION_SUCCESS' => 'D:\\www\\wxjw\\ThinkPHP/../Application/Home/View/default/dispatch_jump.html', 'TMPL_EXCEPTION_FILE' => 'D:\\www\\wxjw\\ThinkPHP/Tpl/think_exception.tpl', 'TMPL_DETECT_THEME' => false, 'TMPL_TEMPLATE_SUFFIX' => '.html', 'TMPL_FILE_DEPR' => '/', 'URL_CASE_INSENSITIVE' => false, 'URL_MODEL' => 3, 'URL_PATHINFO_DEPR' => '/', 'URL_PATHINFO_FETCH' => 'ORIG_PATH_INFO,REDIRECT_PATH_INFO,REDIRECT_URL', 'URL_REQUEST_URI' => 'REQUEST_URI', 'URL_HTML_SUFFIX' => 'html', 'URL_DENY_SUFFIX' => 'ico|png|gif|jpg', 'URL_PARAMS_BIND' => true, 'URL_PARAMS_BIND_TYPE' => 0, 'URL_404_REDIRECT' => '', 'URL_ROUTER_ON' => true, 'URL_ROUTE_RULES' => array ( 'Addons/execute/:_addons/:_controller/:_action' => array ( 0 => 'Home/Addons/execute', ), ), 'URL_MAP_RULES' => array ( ), 'VAR_MODULE' => 'm', 'VAR_CONTROLLER' => 'c', 'VAR_ACTION' => 'a', 'VAR_AJAX_SUBMIT' => 'ajax', 'VAR_JSONP_HANDLER' => 'callback', 'VAR_PATHINFO' => 's', 'VAR_TEMPLATE' => 't', 'VAR_FILTERS' => 'filter_exp', 'HTTP_CACHE_CONTROL' => 'private', 'CHECK_APP_DIR' => true, 'FILE_UPLOAD_TYPE' => 'Local', 'DATA_CRYPT_TYPE' => 'Think', 'AUTOLOAD_NAMESPACE' => array ( 'Addons' => './Addons/', ), 'DATA_AUTH_KEY' => 'H]3{A!&fO|/:XB)i}kd~2"+r@eNs_=*Ka[Go$,DI', 'SHOW_PAGE_TRACE' => true, 'USER_MAX_CACHE' => 1000, 'USER_ADMINISTRATOR' => 1, 'VAR_URL_PARAMS' => '', 'DOCUMENT_MODEL_TYPE' => array ( 2 => '主题', 1 => '目录', 3 => '段落', ), ));Think\Hook::import(array ( 'app_init' => array ( 0 => 'Common\\Behavior\\InitHook', ), 'app_begin' => array ( 0 => 'Behavior\\ReadHtmlCache', ), 'app_end' => array ( 0 => 'Behavior\\ShowPageTrace', ), 'path_info' => array ( ), 'action_begin' => array ( ), 'action_end' => array ( ), 'view_begin' => array ( ), 'view_parse' => array ( 0 => 'Behavior\\ParseTemplate', ), 'template_filter' => array ( 0 => 'Behavior\\ContentReplace', ), 'view_filter' => array ( 0 => 'Behavior\\WriteHtmlCache', ), 'view_end' => array ( ), ));}